C#后台工作者设置e.Result在DoWork中并在WorkCompleted中获得价值

C#2008 SP1

我正在使用后台工作人员

如果其中一个条件失败,我将e.cancel设置为true,并将该字符串分配给e.result。一切都在那里工作

但是,当workCompleted触发时,我测试了e.Result,我得到一个异常“e.result抛出一个systeminvalidoperation类型的异常”。

我想我可以使用一个全局变量来设置DoWork并在完成的工作中进行比较。但这可能不是线程安全的。

任何人都可以告诉我为什么我得到这个e.Result,我该如何解决这个问题?

非常感谢,

    private void bgwPrepareCall_DoWork(object sender, DoWorkEventArgs e)
    {
        // Check to see if the called number is blocked. 
        // If the nubmer is blocked display error message.
        if (this.IsNoGateway(sipUsername, statusDisplay1.PhoneNumber))
        {
            // this.SetIdleState(DialerErrorMessage.GetErrorDescription(12));
            e.Cancel = true;
            e.Result = "NoGateway";
            return;
        }

        if (!this.IsInvalidTelephoneNumber(sipUsername, statusDisplay1.PhoneNumber))
        {
            // this.SetIdleState(DialerErrorMessage.GetErrorDescription(13));
            e.Cancel = true;
            e.Result = "InvalidNumber";
            return;
        }
    }

    private void bgwPrepareCall_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            if (e.Cancelled)
            {
                // Failed
                switch (e.Result.ToString())
                {
                    case "NoGateway":
                        Console.WriteLine("NoGateway: [ Failed ]");
                        break;

                    case "InvalidNumber":
                        Console.WriteLine("InvalidNumber: [ Failed ]");
                        break;

                    default:
                        Console.WriteLine("Unknown");
                        break;
                }
            }
            if (!e.Cancelled)
            {
                // Successfull
                Console.WriteLine("NoGateway: [ ok ]");    
                Console.WriteLine("InvalidNumber: [ ok ]");
            }
        }
        else
        {
            Console.WriteLine("PrepareCall Failed: [ " + e.Error.Message + " ]");
        }
    }
MSDN

If the operation completes
successfully and its result is
assigned in the DoWork event handler,
you can access the result through the
RunWorkerCompletedEventArgs.Result
property.

and

Your RunWorkerCompleted event handler
should always check the Error and
Cancelled properties before accessing
the Result property. If an exception
was raised or if the operation was
canceled, accessing the Result
property raises an exception.

所以如果它没有成功完成(即取消它),它看起来不会奏效。也许考虑退出您的取消细节作为结果(成功)为您的中止情况,检测完成处理程序的差异?

翻译自:https://stackoverflow.com/questions/856313/c-sharp-background-worker-setting-e-result-in-dowork-and-getting-value-back-in-w

转载注明原文:C#后台工作者设置e.Result在DoWork中并在WorkCompleted中获得价值