如何暂停功能,直到按钮被点击
本文关键字:按钮 功能 何暂停 暂停 | 更新日期: 2023-09-27 17:53:28
如何使用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;
}
我可以比较它应该像控制台一样工作。ReadKey暂停函数,直到得到输入。
只要你需要的是取消下载使用WebClient时,点击按钮,你可以使用异步下载:
private WebClient _webClient;
public Form1()
{
InitializeComponent();
_webClient = new WebClient();
_webClient.DownloadFileCompleted += (s, e) =>
{
try
{
if (e.Cancelled)
return;
//do something with your file
}
finally
{
_webClient.Dispose();
}
};
_webClient.DownloadFileAsync(...);
}
private void button1_Click(object sender, EventArgs e)
{
_webClient.CancelAsync();
}
我就是这样做的:
我创建了后台工作器,它允许在执行下载函数时单击按钮。
f函数等待下载函数完成(或中断)。