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...
    }
}

今天的知識就到這里啦,學會了沒有。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM