我有以下代码。我正在尝试制作可以暂停、继续和停止下载器正在运行的后台线程的主窗体按钮(私有线程线程)
Form1.cs
private AutoResetEvent waitHandle = new AutoResetEvent(true);
private Thread thread;
private void ThreadJob()
{
Downloader download = new Downloader();
download.runDownloader();
}
// THREADS button1 is "Download now"-button
private void button1_Click(object sender, EventArgs e)
{
ThreadStart job = new ThreadStart(ThreadJob);
thread = new Thread(job);
thread.IsBackground = true;
thread.Start();
}
此代码在 Windows 窗体上运行。我有所有这些操作的按钮(暂停、继续、停止)
暂停和继续按钮在表单上有代码
private void btnPause_Click(object sender, EventArgs e)
{
waitHandle.WaitOne(); // Need to pause the background thread
}
private void btnContinue_Click(object sender, EventArgs e)
{
waitHandle.Set(); // Need to continue the background thread
}
问题是按下暂停按钮将冻结主窗体而不是后台线程。