假设您有一个辅助方法,该方法执行长时间运行且复杂的数据处理任务,您从后台线程运行,并且您需要该方法的反馈以向用户显示。您认为这些策略中哪一个是最好的方法?
将委托传递给方法,例如 CrunchData(ShowFeedbackDelegate showFeedback)
在包含反馈消息的方法期间在某些关键点引发事件(例如,“处理 1 of 100”)。
引发事件,这就是事件的目的,记住,事件最终是代表......
我会用 BackgroundWorker 做到这一点:
var worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
// do something long running
for (int i = 1; i <= records.Count; i++)
{
DisplayMessage("process " + i + " of " + records.Count);
ProcessRecord(records[i]);
}
};
worker.RunWorkerCompleted+= (s, e) =>
{
// report to user
};
worker.RunWorkerAsync();
无需重新发明轮子,使用 TPL。将长时间运行的操作包装在任务中,并使用Task.ContinueWith方法
public Task<MyCustomStatus> LongRunningOperationAsync()
{
return Task.Factory.StartNew(() =>
{
//Long Running method here
return myCustomStatus;
});
}
和外面
LongRunningOperationAsync().ContinueWith(t=>
{
if(t.Exception == null)
{
//Something bad happen
}
//Task finished
});
TPL 为您提供足够的灵活性来解决大多数异步问题