C#多线程以及更新UI
2015-08-07 11:43
393 查看
C#中线程的基本使用:
新建线程:
using System.Threading;
Thread mThread = new Thread(new ThreadStart(dowork));//dowork为指定方法
启动线程:
mThread.IsBackground = true;
mThread.Start();
终止线程:
mThread.Abort();
利用子线程更新UI的话会导致InvalidOperationException异常
关于如何安全更新UI,见 csdn安全更新UI
在安全更新UI中,有几个概念需要了解。
首先,关于InvalidOperationException异常,是由于创建控件的线程和更改控件的线程不是同一个线程导致的。
因此,安全的方法是使用invoke方法,回溯到主线程中实现更改的方法。因此,子线程中的主要功能是实现逻辑任务,而非更改UI的任务。在处理完逻辑任务后,再使用delegate执行更新UI的方法。
完整代码如下:
private void button1_Click(object sender, EventArgs e)
{
Thread mThread = new Thread(new ThreadStart(dowork));
mThread.IsBackground = true;
mThread.Start();
}
private void dowork() {
String [] text = new String[2];
text[0] = "change"; text[1] = "notchange";
SetText mSetText= new SetText(change);
this.Invoke(mSetText,text[0]);
}
private void change(String text ){
this.status.Text = text;
}
新建线程:
using System.Threading;
Thread mThread = new Thread(new ThreadStart(dowork));//dowork为指定方法
启动线程:
mThread.IsBackground = true;
mThread.Start();
终止线程:
mThread.Abort();
利用子线程更新UI的话会导致InvalidOperationException异常
关于如何安全更新UI,见 csdn安全更新UI
在安全更新UI中,有几个概念需要了解。
首先,关于InvalidOperationException异常,是由于创建控件的线程和更改控件的线程不是同一个线程导致的。
因此,安全的方法是使用invoke方法,回溯到主线程中实现更改的方法。因此,子线程中的主要功能是实现逻辑任务,而非更改UI的任务。在处理完逻辑任务后,再使用delegate执行更新UI的方法。
完整代码如下:
private void button1_Click(object sender, EventArgs e)
{
Thread mThread = new Thread(new ThreadStart(dowork));
mThread.IsBackground = true;
mThread.Start();
}
private void dowork() {
String [] text = new String[2];
text[0] = "change"; text[1] = "notchange";
SetText mSetText= new SetText(change);
this.Invoke(mSetText,text[0]);
}
private void change(String text ){
this.status.Text = text;
}
invoke的作用:在应用程序的主线程上执行指定的委托。一般应用:在辅助线程中修改UI线程( 主线程 )中对象的属性时,调用this.Invoke();
相关文章推荐
- Nopcommerce kendo UI Roxy Fileman控件的汉化
- editui界面常用代码
- STL之priority_queue
- SWT中的UI线程
- Vagrant is attempting to interface with the UI in a way that requires a TTY
- 再说bluetooth4.2
- Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the desi
- StringBuffer与StringBuilder 区别
- Jsp的request
- UVALive 5881 Unique Encryption Keys
- js生成UUID
- setValue: forKeyPath:
- 浅谈:UEO就是SEO的一种
- Android 重写系统控件UI,自定义进度条
- 超详细!iOS 并发编程之 Operation Queues
- druid连接无法回收...
- 解决 UITextView 没有 ShouldReturn 事件
- iOS之整型转换警告Values of type 'NSInteger' should not be used as format arguments;
- Language Guide (proto3)
- UIScrollView 原理详解