Using background worker with multiple classes in C#

前端 未结 5 1291
离开以前
离开以前 2021-01-22 05:35

I am learning to program in C# and have most of the basics down already. I am having trouble using the background worker and using it with multiple classes. This is a backup pro

5条回答
  •  一生所求
    2021-01-22 06:31

    Instead of using BackgroundWorker as-is, consider inheriting from it. This gives you more flexibility about how you get data in and out. Consider this example, where you pass in data in the constructor and get it out with a property:

    class BackgroundDoerOfSomething : BackgroundWorker
    {
        string _SomeData;
    
        public string SomeResult { get; private set; }
    
        public BackgroundDoerOfSomething(string someData)
        {
            _SomeData = someData;
        }
    
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            base.OnDoWork(e);
            // do some processing, and then assign the result
            SomeResult = "some other data";
        }
    }
    

    You would use it like this:

    class DoSomethingInBackground
    {
        BackgroundDoerOfSomething _doer;
    
        void DoSomething()
        {
            _doer = new BackgroundDoerOfSomething("abc");
            _doer.RunWorkerCompleted += _doer_RunWorkerCompleted;
            _doer.RunWorkerAsync();
        }
    
        void _doer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var myResult = _doer.SomeResult;
            // then do something with the result
        }
    }
    

提交回复
热议问题