none
Threading: AsyncCallback : doubt about why Microsoft code sample is not locking collection before adding RRS feed

  • Question

  • Hello!
    I'm learning C# and .NET Framework and I got to this part about threading and using an AsyncCallback Delegate to End an Asynchronous Operation : http://msdn.microsoft.com/en-us/library/ms228972.aspx

    My doubt is this : since we make several BeginGetHostEntry which will trigger several callbacks (I'm assuming all these callbacks may come from different threads - or am I wrong?) should the Add method call to the Array and to the Collection be protected by a lock of some sort?
    I'm speaking about the method callback method  ProcessDnsInformation ; please see link or code sample below.

    Since StringCollection is not thread safe (at least the instance members are not) shouldn't this method be written differently using some sort of lock to protect the the add operation?

    Thanks for your help and attention.
    J.C.
    // The following method is called when each asynchronous operation completes.
    static void ProcessDnsInformation(IAsyncResult result)
    {
    string hostName = (string) result.AsyncState;
    hostNames.Add(hostName);
    try
    {
    // Get the results.
    IPHostEntry host = Dns.EndGetHostEntry(result);
    hostData.Add(host);
    }
    // Store the exception message.
    catch (SocketException e)
    {
    hostData.Add(e.Message);
    }
    finally
    {
    // Decrement the request counter in a thread-safe manner.
    Interlocked.Decrement(ref requestCounter);
    }
    }

    Wednesday, April 30, 2008 3:23 PM

Answers

  • It seems that you're right.  The sample indeed uses methods that are not thread safe and does not synchronize them in any way.  The odds of a race condition are relatively slim because the add operation is cheap compared to the DNS resolve times, but it certainly can happen.
    Wednesday, April 30, 2008 7:50 PM