Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait untill an event raised and then continue code

Tags:

c#

winforms

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?

like image 952
Mohammad Noori Avatar asked Feb 09 '23 02:02

Mohammad Noori


1 Answers

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.

like image 182
Yuval Itzchakov Avatar answered Feb 19 '23 23:02

Yuval Itzchakov