Phantom
Phantom

Reputation: 1700

C# BackgoundWorker return a value

I have the following code in the static class:

public static string ExchangeDataAsync(string request)
{
   BackgroundWorker bgWorker = new BackgroundWorker();

   bgWorker.DoWork             += (obj, e) => ExchangeData(request, e);
   bgWorker.RunWorkerCompleted += (obj, e) => ExchangeCompleted(obj, e);

   bgWorker.RunWorkerAsync(); 

   // I NEED T0 RETURN DATA HERE
}

private static void ExchangeData(string request, DoWorkEventArgs e)
{
  // do some work
  e.Result = some_result;   
}

private static void ExchangeCompleted(object sender, RunWorkerCompletedEventArgs e)
{ 
  MessageBox.Show(e.Result.ToString());   
}

It works OK and I can see my result in ExchangeCompleted method. But how can I access this result in first method? Is there a way to get result from bgWorker object?

I use it in another class like this(so ExchangeDataAsync should return me a value):

string response = Global.ExchangeDataAsync(request);

UPD.

sharpcloud is right. function is not async in that case. do you have any good suggestions how to return value to another class from exchangecompleted method?

Upvotes: 2

Views: 400

Answers (1)

Uzzy
Uzzy

Reputation: 550

You should pass e (instance of RunWorkerCompletedEventArgs) to ExchangeCompleted method. And use Result property of passed e.

Upvotes: 1

Related Questions