向背景工作者发送参数?

时间:2011-01-26 16:36:26

标签: c# backgroundworker

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

private void worker_DoWork(object sender, DoWorkEventArgs e) {

}

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

8 个答案:

答案 0 :(得分:211)

你这样开始:

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.
}

答案 1 :(得分:94)

尽管这是一个已经回答的问题,但我还有另一种选择,即IMO更容易理解:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();

关于处理程序方法:

private void WorkerDoWork(int value, string text) {
    ...
}

答案 2 :(得分:43)

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

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. 

}

答案 3 :(得分:9)

您可以使用DoWorkEventArgs.Argument属性。

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

答案 4 :(得分:6)

查看DoWorkEventArgs.Argument Property

...
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;
    }
}

答案 5 :(得分: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);
      }

现在在后台工作者的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......
        //.....
       }

答案 6 :(得分:4)

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

worker.RunWorkerAsync(5);

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

答案 7 :(得分:4)

您应该始终尝试使用具体类型的复合对象(使用复合设计模式)而不是对象类型列表。谁会记得那些物体到底是什么?考虑稍后维护您的代码......相反,尝试这样的事情:

Public (Class or Structure) MyPerson
                public string FirstName { get; set; }
                public string LastName { get; set; }
                public string Address { get; set; }
                public int ZipCode { get; set; }
End Class

然后:

Dim person as new MyPerson With { .FirstName = “Joe”,
                                  .LastName = "Smith”,
                                  ...
                                 }
backgroundWorker1.RunWorkerAsync(person)

然后:

private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
        MyPerson person = e.Argument as MyPerson
        string firstname = person.FirstName;
        string lastname = person.LastName;
        int zipcode = person.ZipCode;                                 
}