C# .NET - Threads

Hi,

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).

Thanks,

Ilan
breezbackAsked:
Who is Participating?
 
Aleksei_MalkovConnect With a Mentor Commented:
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

0
 
numberkruncherCommented:
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:
http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx
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

0
 
PockyMasterConnect With a Mentor Commented:
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);
tr.Start();

Open in new window

0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
breezbackAuthor Commented:
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.

thanks,

Ilan
0
 
Tony McCreathConnect With a Mentor Technical SEO ConsultantCommented:
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.
0
 
PockyMasterCommented:
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...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.