C# .NET - Threads

Posted on 2009-04-25
Last Modified: 2012-05-06

I would like to have a parser object which I submit url array string[] and it does the work asynchronously.
how do I get the answers after all the threads have finished. Let's say that I will expect an array of results for example the string[]  containing the error code of each page 200, 404, 500 etc.. each retrieved.

How do I make sure all the work is finished and how to continue on the main thread (UI).


Question by:breezback
    LVL 13

    Expert Comment

    In C# you can use the "lock" feature to synchronise access to an object. Use this statement around all blocks of code which access shared resources. The lock statement blocks other threads from accessing the shared variable/property/object until the other thread leaves the lock statement.

    The following link provides a detailed explanation of the "lock" statement:
    Global object for synchronization:
    public static object SyncAccessThreads = new object();
    Thread #1:
    lock (SyncAccessThreads)
       // Write to threads...
    Thread #2:
    lock (SyncAccessThreads)
       // Read from threads...

    Open in new window

    LVL 3

    Accepted Solution

    You can execute parsing asynchronously:
    See BeginInvoke, EndInvoke, IAsyncResult in MSDN

       public class AsyncDemo 
            // The method to be executed asynchronously.
            public string[] TestMethod(string[] urls) 
        // The delegate must have the same signature as the method
        // it will call asynchronously.
        public delegate string AsyncMethodCaller(string[] urls);
    // Create the delegate.
                AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod);
                // Initiate the asychronous call.
                IAsyncResult result = caller.BeginInvoke(array, null, null);
    /// Can do anything in main thread
                // Call EndInvoke to retrieve the results.
                string[] returnValue = caller.EndInvoke(result);

    Open in new window

    LVL 14

    Assisted Solution

    If you would create a wrapper class for your thread, you could raise an event to notify you're done.
    Otherwise you could use a BackGroundWorker.
    public class ThreadDoneEventArgs : EventArgs {}
    public class ThreadClass
    public event EventHandler<ThreadDoneEventArgs> ThreadDoneEvent;
      public void ThreadProc()
        // do your work
       // notify
         EventHandler<ThreadDoneEventArgs>  invoker = ThreadDoneEvent;
         if (invoker != null) ThreadDoneEvent.Invoke(this, new ThreadDoneEventArgs());
    // invocation code
    ThreadClass threadClass = new ThreadClass()
    threadClass.ThreadDoneEvent += ... your event handler
    Thread tr = new Thread(threadClass.ThreadProc);

    Open in new window


    Author Comment

    Well I expected some kind of thread pool, let's say I'm using my parser with maxThreads = 50 threads.

    When the consumer sends string[] urls, it calls a thread on each url , let's say Parse(url) is call asynchronously
    Each thread have the same callback.

    How do I write the code in the callback to wait for all to finish and when all is done notify the consumer with callback.


    LVL 23

    Assisted Solution

    I presume you would be doing async requests, which means threading would be done for you.

    On each response you could flag progress. Once all responses are received you could signal for the GUI to continue. I personally woudn't have the GUI wait but just disable it until all responses are received. This way it will still be responsive.

    I've done it by using a List to keep track of request in progress. Once a reques completes/errors it is removed from the list. The GUIlistens to the list (say by using a BindingList and the ListChanged event) and once it is empty it re-enables its controls.
    LVL 14

    Expert Comment

    There's a ThreadPool object in .NET, only it does not have a method for finding out if processing is done. (There are ways.. but you don't wanna go there).

    My solution can easily work with x amount of threads, just create more class instances...

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
    More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now