.net 您能否链接到使用 BackgroundWorker 的一个很好的示例,而无需将其作为组件放置在表单上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6365887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you link to a good example of using BackgroundWorker without placing it on a form as a component?
提问by Ivan
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?
我记得很多年前(在 2005 年)我在我的代码中使用了 BackgroundWorker 而没有使用可视化组件,但我不记得是如何(不幸的是我非常健忘并且在我停止使用后很快就忘记了一切) . 也许我正在扩展 BackgroundWorker 类。你能链接到一个以这种方式使用 BackgroundWorker 的好例子吗?
回答by CharithJ
Thisarticle explains everything you need clearly.
这篇文章清楚地解释了您需要的一切。
Here are the minimum steps in using BackgroundWorker:
- Instantiate BackgroundWorker and handle the DoWork event.
- 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:
以下是使用 BackgroundWorker 的最少步骤:
- 实例化 BackgroundWorker 并处理 DoWork 事件。
- 调用 RunWorkerAsync,可以选择使用对象参数。
然后它开始运动。传递给 RunWorkerAsync 的任何参数都将通过事件参数的 Argument 属性转发到 DoWork 的事件处理程序。下面是一个例子:
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...
}
}

