Concurrent and parallel programming is really hard to develop. In the old days like .NET 3.x, 2.0 or older, developer can obtain parallel by creating a new thread, maintain their own thread manually; that can harm system performance and execution when not managed carefully.
The past approach (.NET 2.x-3.x)
public static void DoSomething()
{
// do something hard and time consuming like counting with loop
while(true)
{
int x = 3 + 5;
}
}
public static void Run()
{
Thread t = new Thread(new ThreadStart(DoSomething));
t.Start();
t.Join();
// do whatever
}
In the .NET 4.0 (right now I use beta 2), It is easier to develop by using Invoke method from Parallel class
public static void Run()
{
Parallel.Invoke(()=>{ DoSomething(); });
}
Code above will pause main thread and run all code inside Invoke until all running thread terminated. This method deliver more safety than manual ones.
Developer can easily set processor affinity for specific thread by assigning them into the methods. Processor affinity is a bit flags. The documentation is available on microsoft MSDN on class Process with property ProcessorAffinity.
For example, the thread will be executed on second processor, set affinity by
public static void Run()
{
Parallel.Invoke(()=>{
Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)2;
DoSomething(); }
);
}
In task manager. the process will make second processor runs high.
![]()
0 comments:
Post a Comment