亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#中Backgroundworker與Thread的區(qū)別

 更新時間:2022年06月12日 09:33:55   作者:qq_16739693  
本文主要介紹了C#中Backgroundworker與Thread的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

最近項目要用到,窗體Form程序要在后臺開啟幾個子線程,負(fù)責(zé)和其他端進(jìn)行通信,異步讀寫,并且來更改UI。在網(wǎng)上查了有Backgroundworker與Thread兩種方法。

1.Backgroundworker

BackgroundWorker是微軟的在.net Framwork中添加的一個組件,主要對線程的訪問提供了一種安全的方式。簡單的說就是對Thread的一次封裝。

首先介紹一下BackgroundWorker的相關(guān)屬性和方法:

屬性:

  • WorkerReportsProgress:是否可以報告進(jìn)度。
  • WorkerSupportsCancellation:是否允許異步中止。
  • IsBusy:是否在運(yùn)行。
  • CancellationPending:判斷BackgroundWorker是否已經(jīng)異步取消。

方法:

  • RunWorkerAsync:開始執(zhí)行任務(wù)。觸發(fā)DoWork事件
  • ReportProgress:異步提醒,觸發(fā)ProgressChanged事件,但是這個如果可以使用,必須設(shè)置WorkerReportsProgress為True
  • CancelAsync:取消BackgroundWorker操作。

事件:

  • DoWork:執(zhí)行RunWorkerAsync后觸發(fā),異步執(zhí)行的認(rèn)為。
  • ProgressChanged:執(zhí)行ReportProgress時觸發(fā),異步獲得進(jìn)度。
  • RunWorkerCompleted:線程結(jié)束時觸發(fā),主要有成功結(jié)束,發(fā)生異?;蛘呷∠麜r發(fā)生。

一個簡單的例子:

public partial class MainWindow : Window
    {
 
        private BackgroundWorker m_BackgroundWorker;// 申明后臺對象
 
        public MainWindow()
        {
            InitializeComponent();
 
            m_BackgroundWorker = new BackgroundWorker(); // 實例化后臺對象
 
            m_BackgroundWorker.WorkerReportsProgress = true; // 設(shè)置可以通告進(jìn)度
            m_BackgroundWorker.WorkerSupportsCancellation = true; // 設(shè)置可以取消
 
            m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
            m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
            m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
 
            m_BackgroundWorker.RunWorkerAsync(this);
        }
 
 
        void DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            MainWindow win = e.Argument as MainWindow;
 
            int i = 0;
            while ( i <= 100 )
            {
                if (bw.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
 
                bw.ReportProgress(i++);
     
                Thread.Sleep(1000);
 
            }
        }
 
        void UpdateProgress(object sender, ProgressChangedEventArgs e)
        {
            int progress = e.ProgressPercentage;
 
            label1.Content = string.Format("{0}",progress);
        }
 
 
        void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
        {
            if ( e.Error != null)
            {
                MessageBox.Show("Error");
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("Canceled");
            }
            else
            {
                MessageBox.Show("Completed");
            }
        }
 
 
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            m_BackgroundWorker.CancelAsync();
        }
    }  

2.Thread

BackgroundWorker就是一個高級控件,方便使用Thread,后者是前者的靈魂或基礎(chǔ)
直接使用后者難度稍大,但換來的是靈活方便。

Thread的使用就比較麻煩了,對于尤其是對異步提醒來說,需要寫委托,代碼量是很多,但是對于BackgroundWorker來說,卻沒有線程暫停和繼續(xù)的方法。但是對于一般的來說,這些功能也是不用的,而且在微軟的文檔中還提到了,Thread的Resume和Suspend已經(jīng)不推薦使用。

一個簡單的例子:

using System;
using System.Threading;
 
namespace ThreadsComm
{
    public delegate void ReadParamEventHandler(string sParam);
    class MyThread
    {
        public Thread thread1;
        private static ReadParamEventHandler OnReadParamEvent;
        public MyThread()
        {
            thread1 = new Thread(new ThreadStart(MyRead));
            thread1.IsBackground = true;
            thread1.Start();
        }
        public event ReadParamEventHandler ReadParam
        {
            add { OnReadParamEvent += new ReadParamEventHandler(value);}
            remove{ OnReadParamEvent -= new ReadParamEventHandler(value);}
        }
        protected void MyRead()
        {
            int i = 0;
            while (true)
            {
                Thread.Sleep(1000);
                i = i + 1;
                OnReadParamEvent(i.ToString());//觸發(fā)事件
            }
        }
    }
}
using System;
using System.Windows.Forms;
 
namespace ThreadsComm
{
    public partial class Form1 : Form
    {
        private static string param = "";
        public Form1()
        {
            InitializeComponent();
            MyThread thread1 = new MyThread();
            thread1.ReadParam += this.OnRead;
        }
 
        private void OnRead(string sParam)
        {
            param = sParam;
            Object[] list = { this,System.EventArgs.Empty};
            this.lblShow.BeginInvoke(new EventHandler(LabelShow), list);
        }
        protected void LabelShow(Object o, EventArgs e)
        {
            this.lblShow.Text = param;
        }
    }
}

3.總結(jié)

當(dāng)你執(zhí)行的任務(wù)較簡單,不需要復(fù)雜控制時使用BackgroundWorker,較為方便;當(dāng)你要執(zhí)行的任務(wù)需要復(fù)雜控制(如線程同步)時,要自己 創(chuàng)建線程。畢竟,如果我們要實用多個線程,還需要往窗體中加好幾個BackgroundWorker控件。

到此這篇關(guān)于C#中Backgroundworker與Thread的區(qū)別的文章就介紹到這了,更多相關(guān)C# Backgroundworker與Thread內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論