问题描述
我需要让的RunWorkerAsync()
返回列表与LT; FileInfo的>
。我怎样才能从后台工作返回一个对象?
I need to make RunWorkerAsync()
return a List<FileInfo>
. How can I return an object from a background worker?
推荐答案
在对的BackgroundWorker
的DoWork 事件处理程序>(这是工作背景发生)有一种说法 DoWorkEventArgs
。这个对象有一个公共财产的对象结果。当你的工人已经产生的结果(在你的情况下,列表&LT; FileInfo的&GT;
),设置 e.Result
来这和回报。
In your DoWork
event handler for the BackgroundWorker
(which is where the background work takes place) there is an argument DoWorkEventArgs
. This object has a public property object Result. When your worker has generated its result (in your case, a List<FileInfo>
), set e.Result
to that, and return.
现在,你的BackgroundWorker已经完成了它的任务,它触发 RunWorkerCompleted
事件,其中有一个 RunWorkerCompletedEventArgs
对象一个参数。 RunWorkerCompletedEventArgs.Result
将包含从结果你的的BackgroundWorker
。
Now that your BackgroundWorker has completed its task, it triggers the RunWorkerCompleted
event, which has a RunWorkerCompletedEventArgs
object as an argument. RunWorkerCompletedEventArgs.Result
will contain the result from your BackgroundWorker
.
例如:
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int result = 2+2;
e.Result = result;
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int result = (int)e.Result;
MessageBox.Show("Result received: " + result.ToString());
}
这篇关于如何使BackgroundWorker的返回一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!