How to turn an asynchronous method into a synchronous one

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to write an synchronous method Logon(). The method will need to make
asynchronous calls - sending windows messages to other apps and waiting for
replies etc etc etc. I'm wondering what the best way write it as a
synchronous method is.

I can easily write a loop which goes: Thread.Sleep(awhile) until some state
has been changed by event handlers, but is that the best way?
 
You have to use ManualResetEvent for such things. Initiate event and
pass it to an asynchronous method. When a method complete job it have to
invoke Set() method. While an asynchronous method completing execution,
a synchronosu method should invoke WaitOne(). Here is pseudo code for you:

AsyncLogon(ManualResetEvent event)
{
try
{
...
}
finally
{
event.Set();
}
}

SyncLogon()
{
ManualResetEvent event = new ManualResetEvent(false);
AsyncLogon(event);
event.WaitOne();
event.Close();
}

HTH
 
Back
Top