Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a method to a backgroundworker dowork

In the code below, is there a way to instead of always subscribing the updateWorker_DoWork method, pass it a method like this

public void GetUpdates(SomeObject blah)
{
    //...
    updateWorker.DoWork += new DoWorkEventHandler(blah);
    //...
}


public void GetUpdates()
{
    //Set up worker
    updateWorker.WorkerReportsProgress = true;
    updateWorker.WorkerSupportsCancellation = true;
    updateWorker.DoWork += new DoWorkEventHandler(updateWorker_DoWork);
    updateWorker.RunWorkerCompleted +=
        new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
    updateWorker.ProgressChanged +=
        new ProgressChangedEventHandler(updateWorker_ProgressChanged);

    //Run worker
    _canCancelWorker = true;
    updateWorker.RunWorkerAsync();
    //Initial Progress zero percent event
    _thes.UpdateProgress(0);
}
like image 622
James Avatar asked Mar 02 '26 15:03

James


1 Answers

For your RunWorkerAsync() you can pass any argument you like. You can just put a Func() or Action() into it and in your DoWork() you just cast the object back to this specific type and call it.

Examples are here and here.

private void InitializeBackgroundWorker()
{
    _Worker = new BackgroundWorker();

    // On a call cast the e.Argument to a Func<TResult> and call it...
    // Take the result from it and put it into e.Result
    _Worker.DoWork += (sender, e) => e.Result = ((Func<string>)e.Argument)();

    // Take the e.Result and print it out
    // (cause we will always call a Func<string> the e.Result must always be a string)
    _Worker.RunWorkerCompleted += (sender, e) =>
    {
        Debug.Print((string)e.Result);
    };
}

private void StartTheWorker()
{
    int someValue = 42;

    //Take a method with a parameter and put it into another func with no parameter
    //This is called currying or binding
    StartTheWorker(new Func<string>(() => DoSomething(someValue)));

   while(_Worker.IsBusy)
       Thread.Sleep(1);

   //If your function exactly matches, just put it into the argument.
   StartTheWorker(AnotherTask);
}

private void StartTheWorker(Func<string> func)
{
    _Worker.RunWorkerAsync(func);
}

private string DoSomething(int value)
{
    return value.ToString("x");
}

private string AnotherTask()
{
    return "Hello World";
}
like image 118
Oliver Avatar answered Mar 04 '26 05:03

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!