2013-04-22 81 views
0

我有一个布尔函数。我有一个bw,我希望用它来运行这个功能。 我想从函数中获取返回值,有可能吗?布尔函数BackgroundWorker c#

这里是一个示例代码:

void Main() 
{ 
    BackgroundWorker backgroundWorker = new BackgroundWorker(); 
    backgroundWorker.DoWork += (sender1, e1) => testBool(); 
    bool result = backgroundWorker.RunWorkerAsync; 
} 

bool testBool() 
{ 
    return true; 
} 

这可能吗?

谢谢。

+1

不,这是不可能的。使用BackgroundWorker的要点是在另一个线程上运行代码。这需要花时间来计算结果。等待这个结果完全违背了使用worker的点,并且很可能导致死锁,你也可以直接调用testBool()。 – 2013-04-22 13:55:47

回答

1

您可以订阅BackgroundWorker.RunWorkerCompleted事件以接收关于计算终止事实的通知。

里面那个testBool(..)你可以设置全局变量,并且在 里面的RunWorkerCompleted的事件处理程序读取该值。

0

您可以使用e.Result这样的: 第一步:你需要添加RunWorkerCompleted事件。

_bw.RunWorkerCompleted += BwRunWorkerCompleted; 

,并创建功能BwRunWorkerCompleted,线程完成后,这将被解雇。例如:

private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
     { 
      // First, handle the case where an exception was thrown. 
      if (e.Error != null) 
      { 
       MessageBox.Show(e.Error.Message); 
      } 

      // 
      if (e.Result != null) 
      { 
       // test if result is true or false <== HERE YOU GO! 
       if ((Boolean)e.Result == true) 
       { 
        this.Hide(); 
        Form fm = new SFGrilla(ref lr, ref binding); 
        fm.ShowDialog(); 
        this.Close(); 
       } 
      } 
      else 
      { 
       // hide the progress bar when the long running process finishes 
       progressBar.Visible = false; 

       // enable button 
       btnLogin.Enabled = true; 
      } 

     } 

你testbool()应该有合适的参数:

private void testbool(object sender, DoWorkEventArgs doWorkEventArgs) { 
     success = true; 
     doWorkEventArgs.Result = success; 
} 

希望它能帮助。