1

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

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
    }

问题是按下暂停按钮将冻结主窗体而不是后台线程。

4

1 回答 1

4

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

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

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

您还必须更改按钮处理程序,如下所示:

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 以来,有更好的管理线程取消的方法,即使用CancellationTokenSourceand CancellationToken

有关详细信息,请参阅此 Microsoft 文章

于 2013-04-14T14:24:43.220 回答