【发布时间】:2015-06-06 17:39:42
【问题描述】:
如何使用 Thread / BackgroundWorker / Timer / AutoResetEvent 或其他东西来强制函数 f 等待 / 暂停 / 暂停,直到用户点击按钮。
public Form1()
{
InitializeComponent();
if(f())
MessageBox.Show("returned");
}
bool b=false;
private void button1_Click(object sender, EventArgs e)
{
//do something
b=true;
}
bool f()
{
//what to put here
//should be here only after b==true
return true;
}
我可以比较它应该像 Console.ReadKey 一样工作,直到获得输入。
【问题讨论】:
-
为什么不显示消息或做任何你想做的按钮点击?
-
你倒退了。 当按钮被按下时触发函数。
-
约翰所说的。事件对于这样的代码工作得很好。另外,不要将这样的代码放在构造函数中。例如,请尝试
Form.Load。对于更复杂的情况,await可能非常强大 - 但大多数时候它应该不是必需的。 -
重点不是我想一直显示信息。这只是控制点。我需要暂停 f 函数的原因是等待 WebClient.DownloadFile() 函数或通过单击按钮取消它1
标签: c#