C#使用Parallel类进行多线程编程实例
本文实例讲述了C#使用Parallel类进行多线程编程的方法。分享给大家供大家参考。具体如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading; usingSystem.Threading.Tasks; usingSystem.Diagnostics; usingSystem.Runtime.InteropServices; namespaceThreads { classProgram { [DllImport("kernel32.dll",CharSet=CharSet.Auto,SetLastError=true)] publicstaticexternintGetCurrentProcessorNumber(); privatestaticintcriticalSection=0; privatestaticobjectlockObject=newobject(); staticvoidMain(string[]args) { Console.WriteLine("==================Sequentialcalls=============="); Console.WriteLine(); Target(); Target(); Target(); Target(); Target(); Target(); Target(); Target(); Console.WriteLine(); Console.WriteLine("==================Parallelcalls=============="); Console.WriteLine(); Actionaction=newAction(Target); Parallel.Invoke(newAction[]{action,action,action,action,action,action,action,action}); Console.ReadKey(); } privatestaticvoidTarget() { Thread.Sleep(2000); lock(lockObject) { criticalSection++; Console.WriteLine(string.Format("ThreadID:{0}andProcessorID:"+ "{1}CriticalVariableValue:{2}", Thread.CurrentThread.ManagedThreadId, GetCurrentProcessorNumber(),criticalSection)); } } } }
希望本文所述对大家的C#程序设计有所帮助。