ThreadPool Help

V

Vai2000

I have a situation in which threads are spawned for jobs. I am using the
ThreadPool Class to invoke the delegate.
Problem is my calling class exits out before the Threads have completed
their job so I am running into problem. What should I do to prevent it or
find a better way. Since I HAVE to use the ThreadPool class with
QueueUserWorkItem method I don't have alternatives. I don't want the calling
thread to Sleep.

kindly help

TIA

// ========= CODE =================

int main()
{

Console.WriteLine("Started");
ThreadPool.QueueUserWorkItem(new WaitCallback(FlushOff),
dataBuffer.ToString());
Console.WriteLine("Finished");

return 0;

}

void FlushOff(object key)
{
lock{
// something
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

Vai2000,

What I would do is have each method that is called from the threadpool
create a mutex and place this mutex in a shared collection. When the thread
is finished doing its work, it would set the mutex, remove it from the
shared collection, and then exit.

Then, when you want your app to exit, get an array of the mutexes from
the shared collection, and then call the static WaitAll method on the
WaitHandle class, which will wait until all the threads are complete.

Hope this helps.
 
V

Vai2000

Thank you my friend

Nicholas Paldino said:
Vai2000,

What I would do is have each method that is called from the threadpool
create a mutex and place this mutex in a shared collection. When the thread
is finished doing its work, it would set the mutex, remove it from the
shared collection, and then exit.

Then, when you want your app to exit, get an array of the mutexes from
the shared collection, and then call the static WaitAll method on the
WaitHandle class, which will wait until all the threads are complete.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Vai2000 said:
I have a situation in which threads are spawned for jobs. I am using the
ThreadPool Class to invoke the delegate.
Problem is my calling class exits out before the Threads have completed
their job so I am running into problem. What should I do to prevent it or
find a better way. Since I HAVE to use the ThreadPool class with
QueueUserWorkItem method I don't have alternatives. I don't want the calling
thread to Sleep.

kindly help

TIA

// ========= CODE =================

int main()
{

Console.WriteLine("Started");
ThreadPool.QueueUserWorkItem(new WaitCallback(FlushOff),
dataBuffer.ToString());
Console.WriteLine("Finished");

return 0;

}

void FlushOff(object key)
{
lock{
// something
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top