How to use BackGroundWorker in class file?

纵然是瞬间 提交于 2019-12-04 09:23:02
Dummy01

Include:

using System.ComponentModel;

Define it in your class:

private BackgroundWorker BackgroundWorker = new BackgroundWorker();

Initialize it:

BackgroundWorker.WorkerSupportsCancellation = false;
BackgroundWorker.WorkerReportsProgress = true;
BackgroundWorker.DoWork += BackgroundWorker_DoWork;
BackgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( BackgroundWorker_RunWorkerCompleted );

To start it:

BackgroundWorker.RunWorkerAsync();

The usage is exactly the same as you know from Windows Forms.

You should have a look at the Parallel Task Library. There you can start,link and sync asynchronous operations.

http://msdn.microsoft.com/en-us/library/dd537609.aspx

You could also inject an object with an delegate, event, Actio which can be triggered from within the new task to report the progress

for example

You Implement an entity like this

  public class TaskData
    {
        private Action<int> Callback { get; private set; }

        public TaskData(Action<int> callbackAction)
        {
            this.Callback = callbackAction;

        }

        public void TriggerCallBack(int percentageComplete)
        {
            Action<int> handler = Callback;

            if (handler != null)
            {
                handler(percentageComplete);
            }
        }
    }

Than you create a Task with this entity as parameter

TaskData data = new TaskData((percentage)=> Console.WriteLine(percentage + "% completed"));

            Task myTask = new Task(new Action<object>((para)=>
            {
                ((TaskData)para).TriggerCallBack(4);
            }

            ),data);

            myTask.Start();

            Console.ReadLine();

PS: The code is just a quick and dirty hack. feel free to improve it :-)

Please don't use System.ComponentModel.BackgroundWorker, create your own threads instead and implement events if you want to report progress. I had so much bugs with it that I can freely say that it should never ever be used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!