Cheryl wrote:
I have an application that is asynchronous in design. For example.
obj.SendCommand(string cmd)
and the result will be returned in a callback function.
public void obj_OnCommandFinished(object sender, string result)
Will that be possible to turn combine these two functions so that i can
get the result through synchronous calls?
result = SendCommand(string cmd)
If yes, how should I implement that? My current design is to use a flag
to
determine whether the results has returned or not. However, i have to
poll this flag and sleep the thread in order to wait for the result.
Any suggestions?
Thanks!
Hi Cheryl,
What you're after is the [Auto,Manual]ResetEvent classes. They provide the
necessary infrastructure to wait on an event, without having to poll a
flag.
A typical use would be to initialise the event, call SendCommand, then wait
on the event. In the callback function, you would signal the event, which
would wake up the waiters on the event.
Take a look at the following example:
///
using System;
using System.Reflection;
using System.Threading;
public class AsyncObj
{
public delegate void CFH (object sender, string result);
public event CFH CommandFinished;
public void SendCommand (string cmd)
{
Thread isc = new Thread(InternalSendCommand);
isc.Start(cmd);
}
private void InternalSendCommand (object param)
{
Thread.Sleep(1500);
if (CommandFinished != null)
CommandFinished(this, string.Format("Hello, {0}.", param));
}
}
public class EntryPoint
{
private AutoResetEvent _are;
public static void Main ()
{
EntryPoint ep = new EntryPoint();
ep.InternalMain();
}
private void InternalMain ()
{
AsyncObj ao = new AsyncObj();
_are = new AutoResetEvent(false);
ao.CommandFinished += OnCommandFinished;
ao.SendCommand("Tom");
_are.WaitOne();
Console.WriteLine("Finished");
}
private void OnCommandFinished (object sender, string result)
{
Console.WriteLine(result);
_are.Set();
}
}
///
What's of interest is in the EntryPoint class, where the AutoReset event is
constructed and waited on (in InternalMain()), and signalled in
OnCommandFinished(...)
--
Tom Spink
University of Edinburgh