小编典典

向背景工作者发送参数?

c#

假设我想将int参数发送给后台工作者,这如何完成?

private void worker_DoWork(object sender, DoWorkEventArgs e) {

}

我知道什么时候是worker.RunWorkerAsync();,我不明白如何在worker_DoWork中定义它应该采用int参数。


阅读 203

收藏
2020-05-19

共1个答案

小编典典

您可以这样启动:

int value = 123;
bgw1.RunWorkerAsync(argument: value);  // the int will be boxed

然后

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{
   int value = (int) e.Argument;   // the 'argument' parameter resurfaces here

   ...

   // and to transport a result back to the main thread
   double result = 0.1 * value;
   e.Result = result;
}


// the Completed handler should follow this pattern 
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e) 
{
  // check error, check cancel, then use result
  if (e.Error != null)
  {
     // handle the error
  }
  else if (e.Cancelled)
  {
     // handle cancellation
  }
  else
  {          
      double result = (double) e.Result;
      // use it on the UI thread
  }
  // general cleanup code, runs when there was an error or not.
}
2020-05-19