I developed an application with Windows Forms using C#(visual studio 2010). This application should connect to a server and get data, then process that data.
public partial class Form1 : Form
{
public string Result = "";
MyServer server = new MyServer();
public Form1()
{
InitializeComponent();
server.RecieveMessage += new MyServer.RecieveMessageEventHandler(server_RecieveMessage);
}
void server_RecieveMessage(object sender, string message)
{
Result = message;
}
public string SendCommand(string Command)
{
server.Send(Command);
//wait untill RecieveMessage event raised
//process Data is recieved
server.Send(AnotherCommand);
//wait untill RecieveMessage event raised
//process Data is recieved
....
//till i get what i want
return Result;
}
So I want to wait after server.Send(Message)
until I get the result on event. Sometimes it takes 4 to 5 seconds until I get the result. What do I have to do?
One possible way of doing this asynchronously is using TaskCompletionSource<T>
. It could look like this:
public async Task<string> SendMessageAsync(string message)
{
var tcs = new TaskCompletionSource<string>();
ReceiveMessangeEventHandler eventHandler = null;
eventHandler = (sender, returnedMessage) =>
{
RecieveMessage -= eventHandler;
tcs.SetResult(returnedMessage);
}
RecieveMessage += eventHandler;
Send(message);
return tcs.Task;
}
Now, when you want to call it and asynchronously wait for the result, you do this:
public async void SomeEventHandler(object sender, EventArgs e)
{
var response = await server.SendMessageAsync("HelloWorld");
// Do stuff with response here
}
SendMessageAsync
will asynchronously yield control back to the caller until the message is received. Then, once it resumes on the next line, you can alter the response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With