向背景工作者发送参数?

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


private void worker_DoWork(object sender, DoWorkEventArgs e) {


}

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


富国沪深
浏览 275回答 3
3回答

不负相思意

您可以这样启动: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 handlingprivate 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.}

喵喵时光机

尽管这是一个已经回答的问题,但我还是会提出另一个选择,即IMO更容易阅读:BackgroundWorker worker = new BackgroundWorker();worker.DoWork += (obj, e) => WorkerDoWork(value, text);worker.RunWorkerAsync();并在处理程序方法上:private void WorkerDoWork(int value, string text) {    ...}

子衿沉夜

您可以像这样传递多个参数。List<object> arguments = new List<object>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arguments.Add(argument 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arguments.Add(argument 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arguments.Add(argument n);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundWorker2.RunWorkerAsync(arguments);private void worker_DoWork(object sender, DoWorkEventArgs e) {&nbsp; List<object> genericlist = e.Argument as List<object>;&nbsp; extract your multiple arguments from this list and cast them and use them.&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP