How to use the BackgroundWorker event RunWorkerCompleted

后端 未结 3 1856
说谎
说谎 2021-01-18 05:30

All,I already knew the basic usage the BackgroundWorker to handle multiple thread case in the WinForm . And the code structure looks like below.

In the

3条回答
  •  迷失自我
    2021-01-18 06:06

    public class MyWorkerClass
    {
        private string _errorMessage = "";
        public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; }}
    
        public void RunStuff(object sender, DoWorkEventArgs e)
        {
            //... put some code here and fill ErrorMessage whenever you want
        }
    }
    

    then the class where you use it

    public class MyClassUsingWorker
    {
        // have reference to the class where the worker will be running
        private MyWorkerClass mwc = null;
    
        // run the worker
        public void RunMyWorker()
        {
            mwc = new MyWorkerClass();
            BackgroundWorker backgroundWorker1 = new BackgroundWorker();
            backgroundWorker1.DoWork += new DoWorkEventHandler(mwc.RunStuff);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            backgroundWorker1.RunWorkerAsync();
        }
    
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string strSpecialMessage = mwc.ErrorMessage;
    
            if (e.Cancelled == true)
            {
                resultLabel.Text = "Canceled!";
            }
            else if (e.Error != null)
            {
                resultLabel.Text = "Error: " + e.Error.Message;
            }
            else
            {
                resultLabel.Text = e.Result.ToString();
            }
        }
    }
    

提交回复
热议问题