简体   繁体   中英

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?

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
}

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM