Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 948
Vahid Avatar asked Dec 14 '22 20:12

Vahid


1 Answers

As mentioned before, doing IO simultaneous will not gain you much profit.

If it is the calculating that is heavy, yes, you could use a BackgroundWorker, or even better a Task (from the Task Parallel Library).

Task t1 = Task.Run( () => HeavyMethod1() );
Task t2 = Task.Run( () => HeavyMethod2() );

await Task.WaitAll(new Task[] {t1, t2});
like image 93
Patrick Hofman Avatar answered Dec 31 '22 10:12

Patrick Hofman