Search code examples
c#.netwpfmultithreadingbackgroundworker

Execute two separate methods simultaneously


I'm trying two execute two separate methods at the same time using Backgroundworker (or if not possible using another method) to gain performance. The idea is to do heavy calculations in methods.

Is it possible at all?

private readonly BackgroundWorker _worker = new BackgroundWorker();
private readonly BackgroundWorker _worker2 = new BackgroundWorker();

public MainWindow()
{
    InitializeComponent();

    _worker.WorkerReportsProgress = true;
    _worker.WorkerSupportsCancellation = true;
    _worker.DoWork += worker_DoWork;
    _worker.RunWorkerAsync();

    _worker2.WorkerReportsProgress = true;
    _worker2.WorkerSupportsCancellation = true;
    _worker2.DoWork += worker_DoWork2;
    _worker2.RunWorkerAsync();
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    // Do something
}

private void worker_DoWork2(object sender, DoWorkEventArgs e)
{
    //  Do something simultaneously with worker_DorWork
}

Solution

  • Yes, it is possible. A lot of applications today consume multiple threads to do work in parallel. When doing such work, one has to notice the pitfalls too.

    For example, if you have a shared resource consumed by both WorkerA and WorkerB, you will have to do synchronization with any synchronization primitive (such as a Mutex, Semaphore, ManualResetEvent, etc) that is fit for your scenario.

    Also, note that spinning up new threads doesn't come free, there are overheads to each thread such as a 1MB stack for each one created.

    Note, i'd advise you to look into more modern libraries for doing parallel work such as the Task Parallel Library that was introduced in .NET 4.0. Specifically, look into the Task and Parallel classes.

    Edit

    As per your question in the comments, lets see what it looks like to use a Task vs BackgroundWorker:

    BackgroundWorker:

    _worker.WorkerReportsProgress = true;
    _worker.WorkerSupportsCancellation = true;
    _worker.DoWork += worker_DoWork;
    _worker.RunWorkerAsync();
    

    Task:

    var task = Task.Run(worker_DoWork);
    

    or if you're on .NET 4.0:

    var task = Task.Factory.StartNew(worker_DoWork);
    

    You also get the benefits of cancellation, continuation, and the use of async-await with the Task unit, which makes it far easier to do parallel programming.