【问题标题】:Threading start back again after pausing暂停后线程重新开始
【发布时间】:2012-07-29 06:14:38
【问题描述】:

我在我的代码中使用线程,线程是使用函数创建的:

private void InitializeBackgoundWorkers()
{

    for (int f = 0; f < maxThreads; f++)
    {
        listBox1.Items.Insert(0, "Starting Thread : " + (f + 1));
        threadArray[f] = new BackgroundWorker();
        threadArray[f].DoWork +=
            new DoWorkEventHandler(backgroundWorkerFiles_DoWork);
        threadArray[f].RunWorkerCompleted +=
            new RunWorkerCompletedEventHandler(backgroundWorkerFiles_RunWorkerCompleted);
        threadArray[f].ProgressChanged +=
            new ProgressChangedEventHandler(backgroundWorkerFiles_ProgressChanged);
        threadArray[f].WorkerReportsProgress = true;
        threadArray[f].WorkerSupportsCancellation = true;

    }
}

doevent 类似于:

private void backgroundWorkerFiles_DoWork(object sender, DoWorkEventArgs e)
{

    BackgroundWorker worker = sender as BackgroundWorker;

    int flag = 0;

    while (rowCounter < allPostingRows.Tables[0].Rows.Count && flag == 0)
    {

        for (int i = 0; i < maxThreads; i++)
        {

            if (threadArray[i].CancellationPending == true)
            {
                flag = 1;
                threadArray[i].CancelAsync();
                worker.ReportProgress(0, "Thread Paused:");
            }

        }

        if (flag == 0)
        {
             //perform work here
            }
    }
}

在按钮上,我尝试使用以下方法取消线程:

for (int i = 0; i < maxThreads; i++)
{
    threadArray[i].CancelAsync();
}

我是否正确取消了线程?当他们被取消时,我看到列表框中的行说线程已取消,所以它确实进入了取消代码,但一段时间后它重新启动

谢谢

【问题讨论】:

  • 工人是如何开始的?所有工人都重新开始吗?他们会从头开始吗?
  • @PeterRitchie 我减少了所有额外的代码,让它变得简单易用,现在有什么帮助吗?

标签: c# winforms multithreading visual-studio-2010


【解决方案1】:

我不认为你真的了解BackgroundWorkerDoWork 事件处理程序应该是一个工作单元的处理程序。 DoWork 用一个线程调用。在DoWork 处理程序中调用CancelAsync 是没有意义的——这独立于任何和所有其他BackgroundWorker 的处理程序。在DoWork 处理程序中,它应该只检查一个CancellationPending,即发件人的(一旦转换为BackgroundWorker,在您的情况下为worker)。

但是,否则,从 UI 调用 CancelAsync 是取消特定 BackgroundWorker 的正确方法。

后台工作人员不是“线程”。您不是在取消线程,而是在取消工作程序——这使 DoWork 处理程序有机会在完成工作之前退出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2017-01-30
    • 1970-01-01
    相关资源
    最近更新 更多