I’m trying to use the following code bellow to fire multiple thread to consume an HttpWebRequest.
I do a foreach in all possible requests (each request has different data), but when I pass the request to the method of consumption, it seems that it only receives always the last item in the list.
Could someone help me fix this error ?
int pending = requests.Count;
var finished = new ManualResetEvent(false);
foreach (Request request in requests)
{
// Required to close over the loop variable correctly.
Request capture = request;
ThreadPool.QueueUserWorkItem(
(state) =>
{
try
{
ProcessRequest(capture);
}
finally
{
if (Interlocked.Decrement(ref pending) == 0)
{
finished.Set(); // Signal completion of all work items.
}
}
}, null);
}
finished.WaitOne(); //
Why don’t you pass your requests to threads as state object?
Just pass each request as second parameter to the
ThreadPool.QueueUserWorkItem. That is a preferred way of passing data to the thread.