以异步方式运行两个任务并等到它们结束的最快方法

好的,我需要改变这个..

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

这样的事……

 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(); } 

有没有办法在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(); } 

Thread.Join()方法将阻塞执行,直到线程终止,因此加入两个线程将确保foo()仅在两个线程终止后才返回。

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

您需要将Microsoft Async软件包(及其依赖项)添加到您的silverlight项目中。

尽管像Ralph的回答所提到的TPL在Silverlight中不可用,但我真的很喜欢Task模型……那么为什么不写一个类似的瘦线程包装器。

 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()); } } 

那么你可以像TPL一样使用它:

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

在封面下,这使得ThreadPool的责任是将系统中的线程限制为合理的计数。