【发布时间】:2018-07-20 23:46:53
【问题描述】:
我用下面的代码创建了一个空Form来测试不断重启后台worker的性能;
public Form1()
{
InitializeComponent();
BackgroundWorker bw = new BackgroundWorker();
// Do work on Background thread
bw.DoWork += DoWork_WorkerThread;
bw.RunWorkerAsync();
// Return to UI thread and Restart the worker
bw.RunWorkerCompleted += DoWork_WorkerThreadCompleted;
}
private void DoWork_WorkerThread(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(100);
//GC.Collect();
}
private void DoWork_WorkerThreadCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Restart the worker.
// We can verify its the background worker because commenting this out relieves the issue.
((BackgroundWorker)sender).RunWorkerAsync();
}
您可以在任务管理器中看到,每次从DoWork_WorkerThreadCompleted 重新启动worker 时,内存都会跳跃。
我注意到,如果我将GC.Collect() 扔进工作线程,问题就会消失。我是否错误地重新启动了工作程序,或者有没有办法确保在不调用 GC.Collect() 的情况下处理后台线程?
感谢您的宝贵时间。
【问题讨论】:
-
你知道 GC 不会在
IDisposable对象上调用.Dispose()吗? -
旁注:您可能应该在调用 RunWorkerAsync 之前分配 RunWorkerCompleted 事件。
-
另外,启动一个线程会消耗至少 1MB 的 RAM,因为它会创建一个运行时堆栈。
-
感谢大家的回复和对已完成活动的良好呼吁。泰
标签: c# multithreading winforms backgroundworker