c# - Execute two separate methods simultaneously -


i'm trying 2 execute 2 separate methods @ same time using backgroundworker (or if not possible using method) gain performance. idea heavy calculations in methods.

is possible @ 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) {     // }  private void worker_dowork2(object sender, doworkeventargs e) {     //  simultaneously worker_dorwork } 

yes, possible. lot of applications today consume multiple threads work in parallel. when doing such work, 1 has notice pitfalls too.

for example, if have shared resource consumed both workera , workerb, have synchronization synchronization primitive (such mutex, semaphore, manualresetevent, etc) fit scenario.

also, note spinning new threads doesn't come free, there overheads each thread such 1mb stack each 1 created.

note, i'd advise more modern libraries doing parallel work such task parallel library introduced in .net 4.0. specifically, task , parallel classes.

edit

as per question in comments, lets see looks use 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 benefits of cancellation, continuation, , use of async-await task unit, makes far easier parallel programming.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -