Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to run two tasks asynchronously and wait until they end

Tags:

c#

silverlight

Okay I need to change this..

void foo()
{
    DoSomething(1, 0);
    DoSomething(2, 3);
}

to something like this...

void foo()
{
    //this functions is sync.. I need to run them async somehow
    new Thread(DoSomething(1, 0));
    new Thread(DoSomething(2, 3));

    //Now I need to wait until both async functions will end
    WaitUntilBothFunctionsWillEnd();
}

Is there a way to do this in Silverlight?

like image 798
obenjiro Avatar asked Dec 09 '10 19:12

obenjiro


2 Answers

void foo()
{
    var thread1 = new Thread(() => DoSomething(1, 0));
    var thread2 = new Thread(() => DoSomething(2, 3));

    thread1.Start();
    thread2.Start();

    thread1.Join();
    thread2.Join();
}

The method Thread.Join() will block execution until the thread terminates, so joining both threads will ensure that foo() will return only after both threads have terminated.

like image 119
cdhowie Avatar answered Oct 04 '22 20:10

cdhowie


Task task1 = Task.Factory.StartNew( () => {DoSomething(1,0);});
Task task2 = Task.Factory.StartNew( () => {DoSomething(2,3);});
Task.WaitAll(task1,task2);

You'll need to add the Microsoft Async package (and it's dependents) to your silverlight project.

like image 41
Ralph Shillington Avatar answered Oct 04 '22 21:10

Ralph Shillington