gpt4 book ai didi

c# - 后台 worker 和垃圾收集?

转载 作者:可可西里 更新时间:2023-11-01 07:57:14 25 4
gpt4 key购买 nike

我可以在方法中定义后台 worker 吗?

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);
}

问题:如果 Download() 函数下载文件需要很长时间,GC 可以在 RunWorkerCompleted() 执行之前启动并收集 worker 对象吗?

最佳答案

鉴于您实际上并没有使用 BackgroundWorker 的大部分功能,我建议您改用 TPL:

private void DownLoadFile(string fileLocation)
{
Task.Factory.StartNew( () => Download(fileLocation))
.ContinueWith(t => ReportResult(t.Result), TaskScheduler.FromCurrentSynchronizationContext());
}

也就是说,worker 对象一旦运行就不会被垃圾回收,因为 ThreadPool 线程本身会将 worker 作为“已用对象”。在完成事件处理程序执行之前,垃圾收集器将无法收集它,此时将没有用户代码可以到达 BackgroundWorker 的实例。

此外,它可能会阻止此类的实例被垃圾收集,因为闭包使用的实例方法 (ReportResults) 使“this”的实例可访问且不符合条件气相色谱。

关于c# - 后台 worker 和垃圾收集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11088670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com