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
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();