Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke or call more than one method at same time?

Tags:

c#

asp.net

how to call more than one method at same time in my page load in asp.net?? i have 4 methods to called in my page load event. but i want to call all 4 methods and not wait for 1st method to get finish then call 2nd method.

How to achieve this is in asp.net 4.0?

like image 439
Abhishek Ranjan Avatar asked Mar 14 '11 12:03

Abhishek Ranjan


2 Answers

First off, it is important to know if what you are doing is sensible. If they are all CPU-bound, then do not do this, IMO; a web server is already highly threaded, and is usually a busy place to begin with. Chances are high that you will slow the whole thing down by using multiple cores. It'll look great for 1 user, though!

If you are IO-bound, then there are any number of ways to do this; the preferred would be to use the inbuilt async methods of whatever you are talking to, so you can use IOCP rather than regular threads. So for a NetworkStream, you would use BeginRead(...) etc.

Then you need to join everything together. Lots more ways; personally I tend to use Monitor.Wait and Monitor.Pulse, as this avoids going to unmanaged code (many wait-handles are actually OS-provided).

Also note: threading/parallelism comes in a bundle alongside many fun ways to fail; normally you only need to worry overly about static methods/data for synchronization, but if you have multiple threads in a single request doing things: watch out for bumps... there are many.

The next version of .NET is meant to make continuations a lot easier; I need to take a look to see how easily we can apply the current experimental code to IOCP scenarios.

like image 146
Marc Gravell Avatar answered Sep 29 '22 01:09

Marc Gravell


Task[] tasks = new Task[]
{
   new Task(Method0),
   new Task(Method1),
   new Task(Method2),
   new Task(Method3)
}

foreach(var task in tasks)
   task.Start();

Or more shortly

new Task(Method0).Start();
new Task(Method1).Start();
new Task(Method2).Start();
new Task(Method3).Start();
like image 29
Arsen Mkrtchyan Avatar answered Sep 29 '22 02:09

Arsen Mkrtchyan