C# stop execution until an event raises

前端 未结 1 1800
孤街浪徒
孤街浪徒 2020-12-21 20:38

I need to stop execution of the program until user clicks a button. I\'m doing a discrete event simulation and the goal now is to provide simple graphics illustrating the si

相关标签:
1条回答
  • 2020-12-21 20:53

    You can create a method that will return a Task that will be completed when a particular button is next clicked, which it can accomplish through the use of a TaskCompletionSource object. You can then await that task to continue executing your method when a particular button is clicked:

    public static Task WhenClicked(this Button button)
    {
        var tcs = new TaskCompletionSource<bool>();
        EventHandler handler = null;
        handler = (s, args) =>
        {
            tcs.TrySetResult(true);
            button.Click -= handler;
        };
        button.Click += handler;
        return tcs.Task;
    }
    

    This enables you to write:

    DoSomething();
    await button1.WhenClicked();
    DoSomethingElse();
    
    0 讨论(0)
提交回复
热议问题