Make asynchronous call synchronize
I trying to synchronize a asynchronous call.
The regular (async) flow look like:
- Asking the server for data using telnet: 'Session.sendToTarget(message)'
- The app move on doing other things....
- When the server answer ready, the server send the result.
- The app get the result and raise event "OnDataReceived"
The data from the server is critical for the next step so I want to hold EVERYTHING until it's received.
The sync flow should look like:
- Asking the server for data: Session.sendToTarget(message)
- Wait until the data received from the server
Using c#, I tried to sync the operation with 'WaitHandle.WaitOne(TimeToWaitForCallback)' unsuccessfully, It's seems that WaitOne halt the application for receiving incoming messages (I tried as well wait in other thred). Afther TimeToWaitForCallback time pass I get the incoming message that were halt deu to WaitOn开发者_如何学运维e action.
my attempt for making the code sync:
public virtual TReturn Execute(string message)
{
WaitHandle = new ManualResetEvent(false);
var action = new Action(() =>
{
BeginOpertaion(message);
WaitHandle.WaitOne(TimeToWaitForCallback);
if (!IsOpertaionDone)
OnOpertaionTimeout();
});
action.DynamicInvoke(null);
return ReturnValue;
}
The incoming raise this code:
protecte protected void EndOperation(TReturn returnValue)
{
ReturnValue = returnValue;
IsOpertaionDone = true;
WaitHandle.Set();
}
Any ideas?
AutoResetEvent mutex = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
Thread.Sleep(2000);
Console.WriteLine("sleep over");
mutex.Set();
}));
mutex.WaitOne();
Console.WriteLine("done");
Console.ReadKey();
place mutex.Set() to your eventhandler when the async opperation completes...
ps: I like thread over action notation :P
ManualResetEvent can really help you in this case.
http://www.java2s.com/Tutorial/CSharp/0420__Thread/Useamanualeventobject.htm
Below lines
The regular (async) flow look like:
Asking the server for data using telnet: 'Session.sendToTarget(message)'
The app move on doing other things....
When the server answer ready, the server send the result.
The app get the result and raise event "OnDataReceived"
and making it to the following
Asking the server for data: Session.sendToTarget(message)
Wait until the data received from the server
it is as good as blocking request so just call the Session.sendToTarget(message) synchronously. No point of making it asynchronous
精彩评论