Fastest way to run two tasks asynchronously and wait until they end
Okay I need to change this..
void foo()
{
开发者_如何学C 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?
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.
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.
Even though the TPL like Ralph's answer suggested is not available in Silverlight, I really like the Task model... So why not write a thin thread-wrapper that would work similarly.
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 could use this a lot like the TPL:
int param1 = 1;
int param2 = 2;
Task.WaitAll(
new Task( () => DoSomething(param1, param2) ),
new Task( () => DoSomething(param1, param2) )
);
Under the covers this puts the responsibility on the ThreadPool of limiting the threads in the system to a reasonable count.
精彩评论