从WPF中的后台线程返回bool

时间:2013-03-04 10:25:01

标签: c# wpf

public bool function()
{
    bool doesExist = false;          
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (o, ea) =>
        {
            // some work done here
        };

    worker.RunWorkerCompleted += (o, ea) =>
        {
            //somw logic here
            return doesExist;                               
        };
} 

我希望doesExist值作为函数的返回值但是我得到了intellisense错误

  

system.componentmodel。 runworkercompletedeventhandler只返回void,return关键字后面不能跟一个对象表达式

为什么我收到此错误,如何返回bool值?

1 个答案:

答案 0 :(得分:2)

public bool function()
{
   bool doesExist = false;          
   BackgroundWorker worker = new BackgroundWorker();

   worker.DoWork += (o, ea) =>
            {
                 // do some work
                 ea.Result = true; // set this as true if all goes well!
            };

    worker.RunWorkerCompleted += (o, ea) =>
        {
              // since the boolean value is calculated here &
              // RunWorkerCompleted returns void
              // you can create a method with boolean parameter that handle the result.
              Another_Way_To_Return_Boolean(doesExist)


        };
} 


private void Another_Way_To_Return_Boolean(bool result)
{
    if (result)
    {

    }
}