本文实例讲述了c#使用 parallel 类进行多线程编程的方法。分享给大家供大家参考。具体如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading; using system.threading.tasks; using system.diagnostics; using system.runtime.interopservices; namespace threads { class program { [dllimport("kernel32.dll", charset = charset.auto, setlasterror = true)] public static extern int getcurrentprocessornumber(); private static int criticalsection = 0; private static object lockobject = new object(); static void main(string[] args) { console.writeline("==================sequential calls=============="); console.writeline(); target(); target(); target(); target(); target(); target(); target(); target(); console.writeline(); console.writeline("==================parallel calls=============="); console.writeline(); action action = new action(target); parallel.invoke(new action[] { action, action, action, action, action, action, action, action }); console.readkey(); } private static void target() { thread.sleep(2000); lock (lockobject) { criticalsection++; console.writeline(string.format("thread id: {0} and processor id: " + "{1} critical variable value: {2}", thread.currentthread.managedthreadid, getcurrentprocessornumber(), criticalsection)); } } } }
希望本文所述对大家的c#程序设计有所帮助。
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论