我正在查看 .NET 紧凑框架的 OpenNETCF SDF BackgroundWorker 实现中的代码,看起来以下代码不是线程安全的。但是智能设备框架已经存在很多年了,那么我错过了什么?这是线程安全的吗?如果是,为什么?
请注意,我不倾向于发布整个类(class),因为即使 SDF 可以免费使用,但期望客户为 SDF 的许可证付费。如果 SDF 团队中的任何人甚至反对这段教育摘录,那么我将立即撤回该问题。
这是使方法调用出队以在 UI 线程上调用它们的后台线程:
private void ProgressDispatcherProc()
{
this.m_stopThreads = false;
while (!this.m_stopThreads)
{
while (this.m_progressQueue.Count > 0)
{
MethodInvoker method = null;
ProgressChangedEventArgs args = this.m_progressQueue.Dequeue();
if (this.ProgressChanged != null)
{
if (method == null)
{
method = () => this.ProgressChanged(this, args);
}
this.m_guiMarshaller.BeginInvoke(method);
Application.DoEvents();
}
}
Thread.Sleep(this.WorkerReportsProgress ? 5 : 0x3e8);
}
}
变量m_progressQueue
是一个标准的System.Collections.Generic.Queue<>。
我担心的是没有锁定来保护队列,该队列在一个线程中排队并在该线程中出队。我认为在 while (!this.m_stopThreads)
中完成的简单 bool 值循环足够安全,因为据我了解,在 .NET Compact Framework 中,所有变量访问都被视为 volatile 。
最佳答案
我同意它应该有一个锁,至少在 Dequeue
调用周围,如下所示:
lock(m_progressQueue.SyncRoot)
{
ProgressChangedEventArgs args = this.m_progressQueue.Dequeue();
}
并且它可能可以在类的其余部分中使用它们。
关于c# - Compact Framework 上的BackgroundWorker 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12318973/