Can you link to a good example of using BackgroundWorker without placing it on a form as a component?

岁酱吖の 提交于 2019-11-26 11:16:22

问题


I can remember that many years ago (in 2005) I was using BackgroundWorker in my code without using a visual component for it, but I can\'t remember how (unfortunately I am very forgetful and forget everything very soon after I stop using it). Perhaps I was extending BackgroundWorker class. Can you link to a good example of using BackgroundWorker this way?


回答1:


This article explains everything you need clearly.

Here are the minimum steps in using BackgroundWorker:

  1. Instantiate BackgroundWorker and handle the DoWork event.
  2. Call RunWorkerAsync, optionally with an object argument.

This then sets it in motion. Any argument passed to RunWorkerAsync will be forwarded to DoWork’s event handler, via the event argument’s Argument property. Here’s an example:

class Program
{
  static BackgroundWorker _bw = new BackgroundWorker();

  static void Main()
  {
    _bw.DoWork += bw_DoWork;
    _bw.RunWorkerAsync ("Message to worker");
    Console.ReadLine();
  }

  static void bw_DoWork (object sender, DoWorkEventArgs e)
  {
    // This is called on the worker thread
    Console.WriteLine (e.Argument);        // writes "Message to worker"
    // Perform time-consuming task...
  }
}


来源:https://stackoverflow.com/questions/6365887/can-you-link-to-a-good-example-of-using-backgroundworker-without-placing-it-on-a

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