Reputation: 155
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 situation. When the simulation reaches an event worth showing, a method which draws the situation is called. I need the method not to jump back to the simulation core until the user clicks the button (only to be invoked again when an interesting point is reached).
Upvotes: 2
Views: 2076
Reputation: 203847
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();
Upvotes: 6