0

I am building a threading program in C# .Net4.0 and I ran into some issue.

I am using threadpool and callback. Below is my code in Main().

string[] urls = { url1, url2, url3, url4 };
callBack = new WaitCallback(PooledFunc);
for (int i = 0; i < urls.Length; i++)
    ThreadPool.QueueUserWorkItem(callBack, urls[i]);

I also have a function that will get response from the urls

static void PooledFunc(object url)
{
    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

    // Get the response.
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream Answer = response.GetResponseStream();

    // Display the status.
    Console.WriteLine(response.Headers);
    StreamReader _Answer = new StreamReader(Answer);

    string content = _Answer.ReadToEnd();
    Console.WriteLine(content);
}

I put some test prints in there, and with the above code, the program looks like it started all threads but terminate before all of them went through, and everytime is different.

When I put Console.ReadLine(); after the for loop, then it looks like it waits till all threads are done.

Question: Is there a way I can wait till all threads are finished then proceed to the next step without using Console.ReadLine(); ?

1 Answer 1

2

Instead of using ThreadPool.QueueUserWorkItem, you could use Parallel.ForEach to accomplish the same thing:

string[] urls = { url1, url2, url3, url4 };
Parallel.ForEach(urls, url => PooledFunc(url));

Parallel.ForEach will not return until all of the items have been processed.

This also allows you to keep the PooledFunc declaration nicer:

static void PooledFunc(string url) // Can keep this strongly typed
{
    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
2
  • @Reed-Thanks! This works perfect! just another quick question, is there significant downside of opening more threads (or the Parallel)? Like nested/recursinve? For example, opening multiple urls under those (4) urls
    – sora0419
    Jul 3, 2013 at 21:15
  • @sora0419 Each thread has overhead. Too many threads can add overhead and not get you any gains. "Parallel" and similar tools partition to balance that out for you, though. Jul 3, 2013 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.