Search code examples
c#listparametersbackgroundworkerempty-list

How do you pass a List<> of Lists<> to a background worker?


I have a backgroundWorker that is processing two lists. I need to pass the Lists to the worker. the result is empty lists.

Code to pass the Lists (and 2 other parameters). In my test, each list has 20+ items, and the List<> items show that the 20+ items are intact just prior to the call. In the inspector they say "Count" followed by the number of items.

List<Object> arguments = new List<object>();

// Add arguments to pass to background worker
arguments.Add(managerSource);
arguments.Add(managerDestination);
arguments.Add(source as List<EntityTypeContainer>);
arguments.Add(destination as List<EntityTypeContainer>);
// Invoke the backgroundWorker
Main.bgWorkerCopyEntityTypes.RunWorkerAsync(arguments);

I have debugged the DoWork method of the backgroundWorker. On receiving the arguments parameter, they are already "empty". By empty I mean that the entries in the argument List<> show as "Count 0". If I move them into cast variables, they are still 0. I have listed the code below, but the problem manifests itself as soon as the method is invoked.

   private void bgWorkerCopyEntityTypes_DoWork(object sender, DoWorkEventArgs e)
    {
        List<object> arguments = (List<object>)e.Argument;
        RemoteManager managerSource = (RemoteManager)arguments[0];
        RemoteManager managerDestination = (RemoteManager)arguments[1];
        List<EntityTypeContainer> source = (List<EntityTypeContainer>)arguments[2];
        List<EntityTypeContainer> destination = (List<EntityTypeContainer>)arguments[3];

Any help appreciated!


Solution

  • Make a class for the arguments:

    public class BgwArgs
    {
        public string ManagerSource { get; set; }
        public string ManagerDestination { get; set; }
        public List<EntityTypeContainer> Source { get; set; }
        public List<EntityTypeContainer> Destination { get; set; }
    
    }
    

    Make an instance of that class and populate it:

    var bgwargs = new BgwArgs();
    bgwargs.ManagerSource = "whatever";
    // etc.
    

    Pass it:

    Main.bgWorkerCopyEntityTypes.RunWorkerAsync(bgwargs);
    

    And then to get its members:

    private void bgWorkerCopyEntityTypes_DoWork(object sender, DoWorkEventArgs e)
    {
        var myArgs = (BgwArgs)e.Argument;
        var managerSource = myArgs.ManagerSource;
        // etc.
    }