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

北城余情 提交于 2021-02-08 11:42:16

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/64570217/how-do-you-pass-a-list-of-lists-to-a-background-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!