同时调用或调用多个方法?

如何在asp.net的页面加载中同时调用多个方法? 我有4个方法在我的页面加载事件中调用。 但我想调用所有4种方法而不是等待第一种方法完成然后调用第二种方法。

如何实现这一点是在asp.net 4.0?

Task[] tasks = new Task[] { new Task(Method0), new Task(Method1), new Task(Method2), new Task(Method3) } foreach(var task in tasks) task.Start(); 

或者更快

 new Task(Method0).Start(); new Task(Method1).Start(); new Task(Method2).Start(); new Task(Method3).Start(); 

首先,重要的是要知道你在做什么是明智的。 如果它们都受CPU约束,那么要这样做,IMO; Web服务器已经高度线程化,通常是一个繁忙的开始。 有可能通过使用多个核心来降低整体速度。 不过,对于1位用户来说,它看起来很棒!

如果你是IO绑定的,那么有很多方法可以做到这一点; 首选的是使用内置异步方法,无论你正在谈论什么,所以你可以使用IOCP而不是常规线程。 因此,对于NetworkStream ,您将使用BeginRead(...)等。

然后你需要把所有东西加在一起。 还有很多方法; 我个人倾向于使用Monitor.WaitMonitor.Pulse ,因为这样可以避免使用非托管代码(许多等待句柄实际上是OS提供的)。

另请注意:线程/并行性与许多有趣的失败方法捆绑在一起; 通常你只需要担心静态方法/数据的同步,但如果你在一个请求中有多个线程做事:注意颠簸…有很多。

.NET的下一个版本旨在使连续性变得更加容易; 我需要看看我们可以轻松地将当前的实验代码应用于IOCP场景。

你想要做的是进行异步方法调用。

http://www.codeproject.com/KB/cs/AsyncMethodInvocation.aspx

如果你使你的方法异步,它会工作。

(基本存根):

 method1(onReadyCallback1); method2(onReadyCallback2); private void onReadyCallback1() { } 

等等

看一下ThreadPool.QueueUserWorkItem然后在这里举个例子

来自MSDN文档

 using System; using System.Threading; public class Example { public static void Main() { // Queue the task. ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); Console.WriteLine("Main thread does some work, then sleeps."); // If you comment out the Sleep, the main thread exits before // the thread pool task runs. The thread pool uses background // threads, which do not keep the application running. (This // is a simple example of a race condition.) Thread.Sleep(1000); Console.WriteLine("Main thread exits."); } // This thread procedure performs the task. static void ThreadProc(Object stateInfo) { // No state object was passed to QueueUserWorkItem, so // stateInfo is null. Console.WriteLine("Hello from the thread pool."); } }