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

obe*_*iro 5 c# silverlight

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

void foo()
{
    DoSomething(1, 0);
    DoSomething(2, 3);
}
Run Code Online (Sandbox Code Playgroud)

这样的事......

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();
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在Silverlight中执行此操作?

cdh*_*wie 10

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

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

    thread1.Join();
    thread2.Join();
}
Run Code Online (Sandbox Code Playgroud)

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


Ral*_*ton 7

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

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

  • 它不仅不支持.NET 4之前的版本,而且在OP请求的任何版本的Silverlight中也不支持它. (3认同)