C# 异步运行两个任务并等待它们结束的最快方法

C# 异步运行两个任务并等待它们结束的最快方法,c#,silverlight,C#,Silverlight,好的,我需要改变这个 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 wa

好的,我需要改变这个

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);
您需要将包(及其依赖项)添加到silverlight项目中

尽管在Silverlight中没有Ralph建议的答案,但我非常喜欢任务模型。。。那么,为什么不编写一个类似的瘦线程包装器呢

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());
    }
}
然后你可以像第三方物流一样使用它:

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

在封面下,这让线程池负责将系统中的线程数量限制在合理的范围内。

虽然很漂亮,但请注意,Task仅在.NET 4中受支持。如果我需要为这些函数提供一些参数,该怎么办。。例如剂量测定法(参数1、参数2);剂量测定法(参数1、参数2);因此,对象param1和param2对于这两个函数调用都是必需的?不仅在.NET 4之前不支持它,而且在任何版本的Silverlight中都不支持它,因为OP请求它。@ai_boy您可以将任何您想要的东西传递到DoSomething函数中(您对提供的文本1,0,2,3提出了疑问)但是请记住,您将有两个不同的线程同时使用相同的内存,因此您的DoSomething可能必须使用锁块,这可能会破坏整个目的。顺便说一句:在SL中未找到它。。任务类在异步CTP中可用吗?如果我需要为这些函数提供一些参数该怎么办。。例如剂量测定法(参数1、参数2);剂量测定法(参数1、参数2);因此,对象param1和param2对于两个函数调用都是必需的…@Ai_boy:只需替换实际参数:
var thread1=new Thread(()=>DoSomething(param1,param2))
@Ai_boy:你是否试图在这些线程上调整UI?所有对UI的访问必须在UI线程上执行,以避免状态损坏;这里的例外是一种保护措施。尝试调试它并查看异常抛出的位置。我尝试传递WritebleBitmap和一个Point对象。。这两个参数对于两个函数都是相同的。@Ai_boy:但是这些函数做什么呢?他们修改UI了吗?使用线程池来管理任务的创建和启动,使用Linq将ManualResetEvents作为数组收获到waiton,这是一个非常简洁的编码。