Question

I was looking at the code within the OpenNETCF SDF BackgroundWorker implementation for the .NET compact framework and it looks like the following code is not thread-safe. But the Smart Device Framework has been around for ages, so what am I missing? Is this thread-safe and if so, why?

Note that I'm not inclined to post the whole class becasue, even though the SDF is free to use, the expectation is that customers pay for licenses to the SDF. If any of the SDF team object to even this educational excerpt then I will pull the question immediately.

This is the background thread that dequeues method invocations to invoke them on the UI thread:

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

The variable m_progressQueue is a standard System.Collections.Generic.Queue<>.

My concern is there is no locking to protect the queue, which is enqueued in one thread and dequeued in this one. The looping on a simple boolean done in while (!this.m_stopThreads) I assume is safe enough because, as I understand it, in the .NET Compact Framework, all variable accesses treated as volatile.

Was it helpful?

Solution

I'd agree that it should have a lock, at least around the Dequeue call, something like this:

lock(m_progressQueue.SyncRoot)
{
    ProgressChangedEventArgs args = this.m_progressQueue.Dequeue(); 
}

And it could probably use them in the rest of the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top