The fastest way to complete two tasks asynchronously and wait for the end

Ok, 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?

+5
source share
3 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 completes, so combining both threads ensures that it foo()returns only after both threads have completed.

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

You need to add the Microsoft Async package (and its dependents) to your silverlight project.

+7
source

Even if TPL , as Ralph suggested, is not available in Silverlight, I really like the Task model ... So why not write which will work the same way.

using System;
using System.Threading;
using System.Linq;

public class Task {
    ManualResetEvent _mre = new ManualResetEvent(false);

    public Task(Action action) {
        ThreadPool.QueueUserWorkItem((s) => {
            action();
            _mre.Set();
        });
    }

    public static void WaitAll(params Task[] tasks) {
        WaitHandle.WaitAll(tasks.Select(t => t._mre).ToArray());
    }
}

Then you can use this very similar to TPL:

int param1 = 1;
int param2 = 2;
Task.WaitAll(
    new Task( () => DoSomething(param1, param2) ),
    new Task( () => DoSomething(param1, param2) )
);

Under the covers, ThreadPool is responsible for limiting the threads in the system to a reasonable value.

+3
source

All Articles