Search code examples
c#returnbackgroundworker

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?


Solution

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