欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#使用Parallel类进行多线程编程实例

程序员文章站 2023-11-27 13:11:40
本文实例讲述了c#使用 parallel 类进行多线程编程的方法。分享给大家供大家参考。具体如下: using system; using system.col...

本文实例讲述了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#程序设计有所帮助。