加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#,背景工作者

发布时间:2020-12-16 01:47:28 所属栏目:百科 来源:网络整理
导读:我有一个使用BackgroundWorker组件的示例WinForms应用程序.它工作正常,但当我点击取消按钮取消后台线程时,它不会取消线程.当我点击“取消”按钮调用.CancelAsync()方法时,则在RunWorkerCompleted事件处理程序中,e.Cancelled属性始终为false.我想当我点击取消
我有一个使用BackgroundWorker组件的示例WinForms应用程序.它工作正常,但当我点击取消按钮取消后台线程时,它不会取消线程.当我点击“取消”按钮调用.CancelAsync()方法时,则在RunWorkerCompleted事件处理程序中,e.Cancelled属性始终为false.我想当我点击取消按钮时,它应该设置为true.

private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
{
    for (int i = 1; i <= 100; i++)
    {
       // Wait 100 milliseconds.
       Thread.Sleep(100);
       // Report progress.
       if (backgroundWorker1.CancellationPending == true)
       {
           //label1.Text = "Cancelled by user.";
           break;
        }

        backgroundWorker1.ReportProgress(i);
     }
}

private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)
{
    // Change the value of the ProgressBar to the BackgroundWorker progress.
    progressBar1.Value = e.ProgressPercentage;
    // Set the text.
    label1.Text = e.ProgressPercentage.ToString();
}

private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled == true)
    {
        label1.Text = "Canceled!";
    }
    else if (e.Error != null)
    {
        label1.Text = "Error: " + e.Error.Message;
    }
    else
    {
         label1.Text = "Done!";
    }
}

private void button2_Click(object sender,EventArgs e)
{
    if (backgroundWorker1.WorkerSupportsCancellation == true)
    {
        // Cancel the asynchronous operation.
        backgroundWorker1.CancelAsync();
    }
}

解决方法

Canceled属性仍然是false,因为您突破循环,然后允许backgroundworker的DoWork函数以正常方式结束.您永远不会告诉您的后台工作组件实际上已接受待处理的取消.

private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
{
    for (int i = 1; i <= 100; i++)
    {
        // Wait 100 milliseconds.
        Thread.Sleep(100);

        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            break;
        }

        // Report progress.
        backgroundWorker1.ReportProgress(i);
    }
}

区别很重要,因为有时您可能需要在检测到CancellationPending请求时已经完成的回滚工作,因此在您实际完成取消之前可能需要一段时间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读