日期:2014-05-17  浏览次数:21317 次

C#实现多线程界面刷新

?

//这个问题也不知道难倒了多少C#豪杰。比起MFC的界面刷新,在WINFORM中来实现多线程刷新真是很痛苦,故写此文。
//多线程刷新界面主要用到多线程,委托,线程安全、事件等一系列高难度的C#操作。
//关于委托和事件,这有一篇很易懂的文章:hi.baidu.com/anglecloudy/blog/item/a52253ee804d052f2df534ab.html
//===============================================
//先从一个简单的例子说起,是一个没有考虑线程安全的写法:
//先在一个FORM类里面定义一个委托和事件:
  protected delegate void UpdateControlText1(string str);
//定义更新控件的方法
protected void updateControlText(string str)
{
    this.lbStatus.Text = str ;
    return;
}
//在线程函数里面加上下面的内容
UpdateControlText1 update = new UpdateControlText1(updateControlText);//定义委托
this.Invoke(update, "OK");//调用窗体Invoke方法
//这个线程函数必须是类的线程函数,这样用很方便,但有很高的局限性,下面来说个复杂的。

//==============================================
//先定义一个独立的类
public class MoreTime
{
    public delegate void InvokeOtherThead(int i);//委托

    public InvokeOtherThead MainThread;//事件

    public void WaitMoreTime()
    {
        for (int i= 0 ; i<20;i++)
        {
            Thread.Sleep(2000);
            MainThread(i);//调用事件
        }
    }
}
//主函数
public partial class Form1 : Form
{
    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MoreTime mt = new MoreTime();
        mt.MainThread = new MoreTime.InvokeOtherThead(AddToList); //事件响应
        ThreadStart start = new ThreadStart(mt.WaitMoreTime);//起动线程
        Thread thread = new Thread(start);
        thread.Start();
    }

    public void AddToList(int i)   //事件响应函数
    {
        if (this.listBox1.InvokeRequired)
        {
            MoreTime mt = new MoreTime();
            mt.MainThread = new MoreTime.InvokeOtherThead(AddToList);
            this.Invoke(mt.MainThread, new object[] { i});
        }
        else
        {
           listBox1.Items.Add(i.ToString());   //这里一定要是可以瞬时完成的函数
        }
    }
}