问题描述
我需要停止执行程序,直到用户单击按钮为止.我正在进行离散事件模拟,现在的目标是提供说明情况的简单图形.当模拟达到值得显示的事件时,将调用绘制情况的方法.我需要一种方法,直到用户单击按钮时才跳回到仿真核心(只有在达到一个有趣的点时才被调用).
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).
推荐答案
您可以创建一个方法,该方法将返回Task
,该方法将在下次单击特定按钮时完成,该方法可以通过使用a TaskCompletionSource
对象.然后,您可以await
该任务以在单击特定按钮时继续执行您的方法:
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;
}
这使您可以编写:
DoSomething();
await button1.WhenClicked();
DoSomethingElse();
这篇关于C#停止执行直到事件引发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!