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!
Tom Spink - 23 Jun 2007 08:34 GMT
> I have an application that is asynchronous in design. For example.
>
[quoted text clipped - 17 lines]
>
> 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(...)

Signature
Tom Spink
University of Edinburgh
Brian Gideon - 23 Jun 2007 19:14 GMT
> I have an application that is asynchronous in design. For example.
>
[quoted text clipped - 16 lines]
>
> Thanks!
I would encapsulate that logic in another class and use the
IAsyncResult pattern. That class will have BeginSendCommand and
EndSendCommand methods that operate asynchronously. BeginSendCommand
returns an IAsyncResult that you can use to wait on the operation by
calling IAsyncResult.AsyncWaitHandle.WaitOne(). You could also add a
method called SendCommand that operates synchronously and uses the
other methods internally to do that.
Cheryl - 26 Jun 2007 03:15 GMT
Thanks!
>I have an application that is asynchronous in design. For example.
>
[quoted text clipped - 16 lines]
>
> Thanks!