Reputation: 448
My Backgroundworker retrieve and calculate from a path, I need to return an array of string and an array of double.How to pack them together? I know for return one result is like this:
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int result = 2+2;
e.Result = result;
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int result = (int)e.Result;
MessageBox.Show("Result received: " + result.ToString());
}
I also tried to use tuple but it just can't get recognized by my software, I'm using C# 2008 express edition.
How to pack two different type of array together?
Upvotes: 3
Views: 3350
Reputation: 3378
Create a class specifically designed to hold your result.
public class BackgroundWorkResult
{
public List<string> StringList {get;set;}
public List<int> IntList {get;set;}
}
And wrap your results in it when assigning the e.Result = new BackgroundWorkResult() { ... };
It is generally good practice to create a class for each kind of background worker (as for Event Hanlders). In such a way, if in a next version of your code you need another information returned from your BackgroundWorker, you just have to add a property to your result class.
Upvotes: 1
Reputation: 73442
Create a data transfer type. For example:
class MyResult //Name the classes and properties accordingly
{
public string[] Strings {get; set;}
public double[] Doubles {get; set;}
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
//Do work..
e.Result = new MyResult {Strings =..., Doubles = ... };
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MyResult result = (MyResult)e.Result;
//Do whatever with result
}
Upvotes: 5
Reputation: 156948
Create a custom class and pass it to the result.
public class MyClass
{
public MyClass(string[] strings, double[] doubles)
{
this.Strings = strings;
this.Doubles = doubles;
}
public string[] Strings {get;set;}
public double[] Doubles {get;set;}
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
MyClass result = new MyClass(new string[] {"a", "b"}, new double[] {1d, 2d});
e.Result = result;
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MyClass result = (MyClass)e.Result;
// process further
}
Upvotes: 1