C#中多线程实现后台任务的三种方式

第一种:通过Invoke()在应用程序的主线程上执行指定的委托

//新开一个线程,显示当前时间
new Thread(o =>
{                
    while (true)
    {
        Thread.Sleep(1000);
        Invoke((Action)delegate
        {
            this.textBox1.Text= DateTime.Now.ToString();
        }); 
    }
})
{ IsBackground = true }.Start();

第二种:使用类BackgroundWorker

//声明后台工作对象
BackgroundWorker BgWork = new BackgroundWorker();
//绑定事件
private void Form1_Load(object sender, EventArgs e)
{
    BgWork.DoWork += BgWork_Demo;
    BgWork.RunWorkerAsync();
}            
//要后台执行的函数        
void BgWork_Demo(object sender, DoWorkEventArgs e)
{
    try
    {
        Random rd = new Random();
        int i=rd.Next(1,3);
        if (i=1)
        {
            this.Invoke((EventHandler)(delegate { this.textBox1.Text = "成功就行怀孕,大家都会恭喜你!"; }));
        }
        else
            this.Invoke((EventHandler)(delegate { this.textBox1.Text = "但是没有人知道《你被搞了》多少遍才成功!"; }));
    }
    catch (Exception ex)
    {
        MessageBox.Show("程序出来点小问题..." + ex.Message, "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
    }
}

第三种:使用一个Timer结合异步委托方法

Timer tm = new Timer();
private void Form_Load(object sender, EventArgs e)
{
    tm.Interval = 1000;
    tm.Tick += tm_Tick;
    this.BeginInvoke((EventHandler)(delegate { tm.Start(); }));
}

void tm_Tick(object sender, EventArgs e)
{    
    if (1 == 2)
    {
        tm.Stop();        
        //do something...
    }
}

今天的知识就到这里啦,学会了没有。