向背景工作者发送参数?

soo*_*ise 138 c# backgroundworker

假设我想将一个int参数发送给后台工作者,如何实现呢?

private void worker_DoWork(object sender, DoWorkEventArgs e) {

}
Run Code Online (Sandbox Code Playgroud)

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

Hen*_*man 225

你这样开始:

int value = 123;
bgw1.RunWorkerAsync(argument: value);  // the int will be boxed
Run Code Online (Sandbox Code Playgroud)

然后

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.
}
Run Code Online (Sandbox Code Playgroud)

  • 我怎么能做两个论点? (37认同)
  • @soo:使用辅助类或`Tuple <A,B>`(C#4 +)(编辑:是的,使用一个对象将其打包.请参阅例如DoWorkEventArgs self). (23认同)
  • 或者我发送一个充满多个参数的对象? (3认同)

dca*_*iro 96

虽然这是一个已经回答的问题,但我还有另外一个选择,即IMO更容易阅读:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
Run Code Online (Sandbox Code Playgroud)

并在处理程序方法上:

private void WorkerDoWork(int value, string text) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 我不知道IMO的意思,我认为这是一个C#的事情.我用Google搜索"C#IMO"并登陆这里得到了答案... lol https://www.quantnet.com/threads/cc-vba-or-java.11433/ (12认同)

Zai*_*Ali 44

你可以像这样传递多个参数.

List<object> arguments = new List<object>();
                    arguments.Add(argument 1);
                    arguments.Add(argument 1);
                    arguments.Add(argument n);


                    backgroundWorker2.RunWorkerAsync(arguments);

private void worker_DoWork(object sender, DoWorkEventArgs e) {

  List<object> genericlist = e.Argument as List<object>;
  extract your multiple arguments from this list and cast them and use them. 

}
Run Code Online (Sandbox Code Playgroud)

  • 这在维护方面是个坏主意。您应该在 List&lt;object&gt; 上使用具体类型,因为至少您将能够弄清楚自己在做什么(请参阅下面我的回答中的示例) (2认同)

Dav*_*eer 9

您可以使用该DoWorkEventArgs.Argument物业.

可以在Microsoft的站点上找到完整的示例(甚至使用int参数):


Jay*_*ggs 6

查看DoWorkEventArgs.Argument属性:

...
backgroundWorker1.RunWorkerAsync(yourInt);
...

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Do not access the form's BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = sender as BackgroundWorker;

    // Extract the argument.
    int arg = (int)e.Argument;

    // Start the time-consuming operation.
    e.Result = TimeConsumingOperation(bw, arg);

    // If the operation was canceled by the user, 
    // set the DoWorkEventArgs.Cancel property to true.
    if (bw.CancellationPending)
    {
        e.Cancel = true;
    }
}
Run Code Online (Sandbox Code Playgroud)


alp*_*use 5

您需要RunWorkerAsync(object)方法和DoWorkEventArgs.Argument属性。

worker.RunWorkerAsync(5);

private void worker_DoWork(object sender, DoWorkEventArgs e) {
    int argument = (int)e.Argument; //5
}
Run Code Online (Sandbox Code Playgroud)


suj*_*jay 5

如果你想传递多种类型的参数,你可以试试这个,首先将它们全部添加到Object类型的数组中,并将该对象传递给RunWorkerAsync()这里是一个例子:

   some_Method(){
   List<string> excludeList = new List<string>(); // list of strings
   string newPath ="some path";  // normal string
   Object[] args = {newPath,excludeList };
            backgroundAnalyzer.RunWorkerAsync(args);
      }
Run Code Online (Sandbox Code Playgroud)

现在在后台工作者的doWork方法中

backgroundAnalyzer_DoWork(object sender, DoWorkEventArgs e)
      {
        backgroundAnalyzer.ReportProgress(50);
        Object[] arg = e.Argument as Object[];
        string path= (string)arg[0];
        List<string> lst = (List<string>) arg[1];
        .......
        // do something......
        //.....
       }
Run Code Online (Sandbox Code Playgroud)

  • +1.以这种方式发送参数还避免了必须在每次运行时启动新的后台工作以避免重复.(至少在我的应用程序中).请参阅下面与此问题相关的评论.另外http://stackoverflow.com/a/12231431/503621&http://stackoverflow.com/questions/12507602/c-sharp-backgroundworker-keep-on-running-dowork (2认同)