BackgroundWorker的 - CancellationPending改变为false RunWorkerCompleted。为什么? [英] BackgroundWorker - CancellationPending changing to false in RunWorkerCompleted. Why?

查看:739
本文介绍了BackgroundWorker的 - CancellationPending改变为false RunWorkerCompleted。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取消的BackgroundWorker后,在DoWork的,该CancellationPending是真实的,但是当他谈到RunWorkerCompleted中,CancellationPending是假的。 ?我不知道我做错

After canceling the BackGroundWorker, in the DoWork, the CancellationPending is true but when he comes to the RunWorkerCompleted, the CancellationPending is false. I dont know what did I do wrong?

static BackgroundWorker b1;

static void Main(string[] args)
{
    b1=new BackgroundWorker();
    b1.DoWork += new DoWorkEventHandler(work1);
    b1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completed);
    b1.WorkerSupportsCancellation = true;
    b1.RunWorkerAsync("Hellow");
    Console.ReadLine();
}

private static void completed(object sender, RunWorkerCompletedEventArgs e)
{
    if (((BackgroundWorker)sender).CancellationPending)
        Console.WriteLine("Canceled!");
    else
        Console.WriteLine("Result:" + e.Result);//it goes here every time
}

private static void work1(object sender, DoWorkEventArgs e)
{
    ((BackgroundWorker)sender).CancelAsync();
    if (((BackgroundWorker)sender).CancellationPending)
    {
        e.Cancel = true;
    }
}



顺便说一句,我怎样才能添加一个错误发生在DoWork的到RunWorkerCompletedEventArgs.Error为shoing它给用户?

By the way, How can I add an error that occur in the DoWork to the RunWorkerCompletedEventArgs.Error for shoing it up to the user?

推荐答案

我相信CancellationPending属性是使用后台操作(在你的WORK1法)中。它会告诉你所请求的后台操作被取消的背景工人。一旦RunWorkerCompleted事件被调用时,后台工作已经完成的工作,以取消请求,并因此取消不再悬而未决。

I believe the CancellationPending property is for use during the background operation (in your work1 method). It will tell the background worker that you have requested the background operation be canceled. Once the RunWorkerCompleted event is called, the background worker has done the work to cancel the request, and therefore the cancellation is no longer pending.

编辑:RunWorkerCompletedEventArgs具有取消属性,会告诉你,如果后台操作被取消

the RunWorkerCompletedEventArgs has a Cancelled property that will tell you if the background operation was cancelled.

如果。你扔从DoWork的方法(在你的情况WORK1),应该由BackgroundWorker的捕获和填充RunWorkerCompletedEventArgs的错误属性的例外。

If you throw an exception from the DoWork method (work1 in your case), it should be caught by the BackgroundWorker and populate the Error property of the RunWorkerCompletedEventArgs.

这篇关于BackgroundWorker的 - CancellationPending改变为false RunWorkerCompleted。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆