Link to home
Start Free TrialLog in
Avatar of noulouk
noulouk

asked on

Delegate BeginInvoke and ManualResetEvent.WaitOne()

Hello Experts,

Here is an example:

ManualResetEvent waiter;
delegate DoWorkDelegate;

void DoWork()
{
       waiter.WaitOne();
}

void SubMethodnvoke()
{
DoWorkDelegate.BeginInvoke(DoWork);
}

I do something like this when I open Submethods in my app.
I want to know how many submethods I can open.
I think this asynchronous delegate works as a ThreadPool, so if I open more than the pool threads limit (ie 25 threads by default) I will probably have some troubles.

In fact, I don't know how it works in background. In the msdn documentation, ManualResetEvent.WaitOne() blocks the Thread until it receives a signal. But I hope this is not really the case and the Thread is reused in background to run some other jobs because if I have more than 25 waiting threads in the queue my app is dead.
Is ManualResetEvent.WaitOne() really blocking a Thread or is there any job in the ThreadPool to let those waiting Threads not block all others in the queue ?

Thanks in advance for your help.
Avatar of photowhiz
photowhiz
Flag of Canada image

That code cannot possibly work; waiter and DoWorkDelegate are uninitialized. You are not saving the AsyncResult from BeginInvoke, nor calling EndInvoke.

Of course WaitOne will block, that is its purpose. If you don't want to block don't call WaitOne.

There is a good introduction to asynchronous methods at http://www.codeproject.com/KB/cs/AsyncMethodInvocation.aspx.
Avatar of noulouk
noulouk

ASKER

Sorry, but the problem is not in my code:
void SubMethodnvoke()
{
...
DoWorkDelegate.BeginInvoke(DoWork);
...
}
If you want.

My question is:
Does the machine free a thread in background if you use WaitOne() or Sleep(10000) ?
I can't find any doc and I'm afraid if a thread really sleeps during 10000 and is not free by the system. It seems to me to be a really bad management of the ThreadPool threads, doesn't it ?
If I run more waiting threads than the pool threads limit, my app is dead.

Hope you understand what information I ask.
ASKER CERTIFIED SOLUTION
Avatar of mastoo
mastoo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial