发送参数为后台工作? [英] Sending Arguments To Background Worker?

查看:108
本文介绍了发送参数为后台工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我想送一个int参数后台工作,这可怎么实现的?

Let's say I want to sent an int parameter to a background worker, how can this be accomplished?

private void worker_DoWork(object sender, DoWorkEventArgs e) {

}

我知道这是worker.RunWorkerAsync();我不明白如何在worker_DoWork定义,它应该采取一个int参数。

I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker_DoWork that it should take an int parameter.

推荐答案

您象这样开始:

int value = 123;
bgw1.RunWorkerAsync(value);  // 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.
}

这篇关于发送参数为后台工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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