How to block until an event is fired in c#

前端 未结 4 681
孤街浪徒
孤街浪徒 2020-12-23 09:29

After asking this question, I am wondering if it is possible to wait for an event to be fired, and then get the event data and return part of it. Sort of like this:

4条回答
  •  既然无缘
    2020-12-23 09:48

    If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

        TaskCompletionSource tcs = null;
    
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            tcs = new TaskCompletionSource();
            await tcs.Task;
            WelcomeTitle.Text = "Finished work";
        }
    
        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            tcs?.TrySetResult(true);
        }
    

    This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

    await tcs.Task;
    

    to

    await Task.WhenAny(tcs.Task, Task.Delay(25000));
    if (tcs.Task.IsCompleted)
        WelcomeTitle.Text = "Task Completed";
    else
        WelcomeTitle.Text = "Task Timed Out";
    

提交回复
热议问题