Skip to main content
 首页 » 编程设计

c#之使用 AutoResetEvent.WaitOne() 和 .Set() 暂停后台线程

2024年02月13日11thcjp

我有以下代码。我正在尝试为主窗体制作按钮,它可以暂停、继续和停止下载程序正在运行的后台线程(私有(private)线程线程)

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 
    } 

问题是按下暂停按钮会卡住主窗体而不是后台线程。

请您参考如下方法:

必须能够暂停的是runDownloader()。

它需要在等待句柄上定期调用 waitHandle.WaitOne()。

您的 WaitHandle 必须是 ManualResetEvent,而不是 AutoResetEvent 并且您应该初始化它以便发出信号(除非您想以“暂停”状态启动您的线程状态)。

您还必须按如下方式更改按钮处理程序:

private void btnPause_Click(object sender, EventArgs e) 
{ 
    waitHandle.Reset(); // Need to pause the background thread 
} 
 
private void btnContinue_Click(object sender, EventArgs e) 
{ 
    waitHandle.Set(); // Need to continue the background thread 
} 

这意味着您必须能够将 waitHandle 传递给线程,以便它可以等待。

但是,自 .Net 4 以来,有更好的方法来管理线程取消,即使用 CancellationTokenSource和 CancellationToken .

参见 this Microsoft article了解详情。