Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple result from backgroundworker C#

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?

like image 611
asdjkag Avatar asked Jun 11 '26 02:06

asdjkag


2 Answers

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
}
like image 152
Sriram Sakthivel Avatar answered Jun 12 '26 15:06

Sriram Sakthivel


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
}
like image 37
Patrick Hofman Avatar answered Jun 12 '26 16:06

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!