Search code examples
c#winformsbackgroundworker

BackgroundWorker having everything passed as delegate


I want to pass the whole code to the BackgroundWorker DoWork event. I see it like that

     var c = (MethodInvoker)delegate
     {
           object all = z.bg_getAllPlugins("size=10");
           propertyGrid1.Invoke((MethodInvoker)delegate
           {
                propertyGrid1.SelectedObject = all;
           });
     };
     call.RunWorkerAsync(c);

But when I try to invoke it

    private void call_DoWork(object sender, DoWorkEventArgs e)
    {
        Invoke(e.Argument);
    }

, it invokes it on the Main thread, thus making the BackgroundWorker not doing it's job. Is it possible for the BackgroundWorker to have a Delegate invoked in DoWork thread?

Now just to pass the argument, being a delegate MethodInvoker.


Solution

  • The problem is that you're calling Invoke from the call_DoWork method - and Control.Invoke invokes a delegate on the UI thread. You just want to invoke the delegate on the current thread:

    var work = (MethodInvoker) e.Argument;
    work();
    

    (That's assuming your delegate is always a MethodInvoker of course.)