About Asynchronous method invocation

M

Morgan Cheng

Asynchronous method model generally has a callback delegate as
argument. The delegate will be called when some WaitHandle is set or
time out. And, one more argument is used as state object to transfer
any customized data into callback delegate. I believe that is un-
necessary.

For example,
public static RegisteredWaitHandle RegisterWaitForSingleObject (
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce
)

public delegate void WaitOrTimerCallback (
Object state,
bool timedOut
)
the parameter state is to used as first argument to delegate
WaitOrTimerCallback. We can package something into a customized
object, and cast it back to real value in delegate to extract info.

With the help of anonymous delegate, the state object can always be
ignored.

int foo = 23;
string bar = "abc";

AutoResetEvent ev = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(
ev,
delegate(object state, bool timedOut)
{
Console.WriteLine("{0}, {1}", foo, bar); //just
use it directly
}
null, //can always be null
2000,
true
);

Is there any problem in my understanding?
Thanks,
 
S

Samuel R. Neff

The asynchronouse method invocation architecture predates anonymous
delegates. Also, not everyone wants to use an anonymous delegate
every time to pass state data, sometimes the state object is better
for the situation (particularly when using a generic callback delegate
that used in many places).

HTH,

Sam
 

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