我可以在方法中定义一个背景工作吗?背景工作者和垃圾收集?
private void DownLoadFile(string fileLocation){
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler((obj, args) => {
// Will be executed by back ground thread asynchronously.
args.Result = Download(fileLocation);
});
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((obj, args) => {
// will be executed in the main thread.
Result r = args.Result as Result;
ReportResult(r);
});
worker.RunWorkerAsync(fileLocation);
}
问题:如果下载()函数需要很长的时间来下载文件,可以GC踢和RunWorkerCompleted之前收集工人对象()被执行?
我建议使用委托(Action(Of String)会做),然后调用BeginInvoke。在代码中我看不到BackgroundWorker的任何需求。您仍然可以在方法完成时附加一个事件。 – JDB
更好的方法是使用'QueueUserWorkItem'将其添加到线程池队列中:http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx –
@J ...线程池很好,但它确实使得在正确的SynchronizationContext *上处理回调*变得更加困难。不过,TPL可以很好地处理。 –