C# .NET - Threads

Posted on 2009-04-25
Medium Priority
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

ID: 24234160
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


Accepted Solution

Aleksei_Malkov earned 400 total points
ID: 24234586
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

PockyMaster earned 200 total points
ID: 24234903
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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.


Author Comment

ID: 24235010
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

by:Tony McCreath
Tony McCreath earned 400 total points
ID: 24235099
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

ID: 24241089
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...

Featured Post

Free recovery tool for Microsoft Active Directory

Veeam Explorer for Microsoft Active Directory provides fast and reliable object-level recovery for Active Directory from a single-pass, agentless backup or storage snapshot — without the need to restore an entire virtual machine or use third-party tools.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
Suggested Courses
Course of the Month13 days, 18 hours left to enroll

807 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