IT

백그라운드 작업자에게 인수를 보내시겠습니까?

lottoking 2020. 6. 25. 07:41
반응형

백그라운드 작업자에게 인수를 보내시겠습니까?


백그라운드 작업자에게 int 매개 변수를 보내려면 어떻게해야합니까?

private void worker_DoWork(object sender, DoWorkEventArgs e) {

}

이것이 worker.RunWorkerAsync ();이라는 것을 알고 있습니다. worker_DoWork에서 int 매개 변수를 사용해야한다고 정의하는 방법을 이해하지 못합니다.


다음과 같이 시작하십시오.

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

이것이 이미 답변 된 질문이지만 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>();
                    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. 

}

DoWorkEventArgs.Argument속성을 사용할 수 있습니다 .

전체 예제 (int 인수를 사용하더라도)는 Microsoft 사이트에서 찾을 수 있습니다.


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

you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :

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

Now in the doWork method of background worker

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

You need RunWorkerAsync(object) method and DoWorkEventArgs.Argument property.

worker.RunWorkerAsync(5);

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

You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:

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

And then:

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

and then:

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

참고URL : https://stackoverflow.com/questions/4807152/sending-arguments-to-background-worker

반응형