文章来自 http://lovefly.blog.51cto.com/914912/274505   看到这篇文章的解释 我大概理解了为什么需要用委托了.

 

C#为什么多线程控制winform需要用委托?比如我新起了一个线程A,在A线程里要对winform的list控件里显示数据,我需要用一个委托函数来实现。
 
因为winform是主线程创建的,你用另外一个线程来调用它就可能会出现两个线程同时访问同一个资源的问题,这个时候很容易出现错误,比如A线程改变窗口的颜色为红色,B线程取窗口的颜色,如果这两个线程正好碰到一起,可能A略先于B,那么就是B取出来的红色,如果略后于那么就是原来的颜色,而这和CPU的繁忙度、时间片的轮转是相关的,是一种随机的情况,那么B取出来的颜色就不可靠了,因此为了避免这种状况采用委托,B线程向A线程发出委托,由A线程来完成取色工作,那么可以保证取色工作的稳定性,结果也可靠
如果你实在想通过另一个线程访问winform,可以在窗口的构造函数中加入 Control.CheckForIllegalCrossThreadCalls = false; 这样可以屏蔽这个错误,不过建议还是用委托
 
这需要用到委托. 你先声明一个委托,然后,把一个操作界面的函数托给他. 你的线程里只要调用这个委托就可以了.
 
C#试写一个多线程问题(委托,Invoke(),beginInvoke())
using System; 
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;

namespace _
{
public partial class Form1 : Form
{
public delegate void del(string str);
public delegate void del1(string str1);
Thread thread1,thread2;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
this.thread1 = new Thread(new ThreadStart(this.sa));
this.thread1.Start();
//MessageBox.Show(this,);
this.button1.Enabled = false;
//获取当前的线程好
int thread1id = Thread.CurrentThread.GetHashCode();
string strThreadId = Convert.ToString(thread1id);
MessageBox.Show(this,strThreadId);
}

private void progressSet(string text)
{
progressBar1.Value = 0;
progressBar1.Maximum = 999999;
for (int i = 0; i < 999999; i++)
{
progressBar1.Value++;
}
progressBar1.Value = 0;
}

private void sa()
{
del pro = new del(progressSet);
this.Invoke(pro, new object[] { "hello" });
}

private void button2_Click(object sender, EventArgs e)
{
this.thread2 = new Thread(this.sa1);
thread2.Start();
this.button2.Enabled = false;
//获取当前的线程好
int thread2id = Thread.CurrentThread.GetHashCode();
string strThreadId = Convert.ToString(thread2id);
MessageBox.Show(this, strThreadId);
}

private void sa1()
{
//其他操作
//比如将界面的TextBox内容设置一下
del1 mi1 = new del1(UpdateTextBox);
this.Invoke(mi1, new object[] { "我是一个文本框" });
}

//更新界面的方法
private void UpdateTextBox(string str)
{
//更新
this.textBox1.Text = str;
}
}
}
 posted on 2012-02-25 21:41  纵欲  阅读(491)  评论(0编辑  收藏  举报