Chinaunix首页 | 论坛 | 博客
  • 博客访问: 756114
  • 博文数量: 96
  • 博客积分: 2023
  • 博客等级: 上尉
  • 技术积分: 1738
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-15 10:03
文章分类

全部博文(96)

文章存档

2014年(11)

2012年(85)

分类: 嵌入式

2012-04-20 16:26:51

    C#编程中如果想要实现多线程,我们可以自己新建Thread,也可以使用C#自带的ThreadPool(它提供一个线程池,该线程池可用于发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器)。现在提供两个例子(控制台程序和窗体程序):
控制台程序:

点击(此处)折叠或打开

  1. public class Fibonacci
  2.     {
  3.         public Fibonacci(int n, ManualResetEvent doneEvent)
  4.         {
  5.             _n = n;
  6.             _doneEvent = doneEvent;
  7.         }

  8.         //Wrapper method for use with thread pool

  9.         public void ThreadPoolCallback(Object threadContext)
  10.         {
  11.             int threadIndex = (int)threadContext;
  12.             Console.WriteLine("thread {0} started...", threadIndex);
  13.             _fibOfN = Calculate(_n);
  14.             Console.WriteLine("thread {0} result calculated...", threadIndex);
  15.             _doneEvent.Set();
  16.         }

  17.         public int Calculate(int n)
  18.         {
  19.             if (n <= 1)
  20.             {
  21.                 return n;
  22.             }
  23.             return Calculate(n - 1) + Calculate(n - 2);
  24.         }
  25.         public int N { get { return _n; } }
  26.         public int FibOfN { get { return _fibOfN; } }

  27.         private int _n;
  28.         private int _fibOfN;
  29.         private ManualResetEvent _doneEvent;
  30.     }
  31.     class Program
  32.     {
  33.         static void Main(string[] args)
  34.         {
  35.             const int FibonacciCaculations = 10;
  36.             //One event is used for each Fibonacci object

  37.             ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCaculations];
  38.             Fibonacci[] fibArray = new Fibonacci[FibonacciCaculations];
  39.             Random r = new Random();
  40.             //开始使用线程池

  41.             Console.WriteLine("launching {0} tasks...", FibonacciCaculations);
  42.             for (int i = 0; i < FibonacciCaculations; i++)
  43.             {
  44.                 doneEvents[i] = new ManualResetEvent(false);
  45.                 Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
  46.                 fibArray[i] = f;
  47.                 ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
  48.             }
  49.             //等待线程池中所有计算完成

  50.             WaitHandle.WaitAll(doneEvents);
  51.             Console.WriteLine("All calculations are complete.");
  52.             //Display the results

  53.             for (int i = 0; i < FibonacciCaculations; i++)
  54.             {
  55.                 Fibonacci f = fibArray[i];
  56.                 Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
  57.             }
  58.             Console.Read();
  59.         }
  60.     }
窗体程序:
①多线程管理类

点击(此处)折叠或打开

  1. //用于显示状态的代理方法类型定义

  2.     public delegate void DelegateShowStateInfo(string state);

  3.     ///

  4.     /// 测试器

  5.     ///

  6.     public class QueueTester
  7.     {
  8.         private static bool _Exit = false; //标记是否已中断测试程序

  9.         private static Form _OwnerForm; //测试的窗体

  10.         private static DelegateShowStateInfo _StateMethod;

  11.         private static IList _Queue1 = new ArrayList(); //Queue1的数据

  12.         private static IList _Queue2 = new ArrayList(); //Queue2的数据

  13.         private static IList _Queue3 = new ArrayList(); //Queue3的数据



  14.         public static void StopThread()
  15.         {
  16.             _Exit = true;
  17.             _OwnerForm = null;
  18.         }

  19.         public static void Testing(Form sender, DelegateShowStateInfo method)
  20.         {
  21.             _StateMethod = method;
  22.             _OwnerForm = sender;
  23.             _Exit = false;

  24.             ThreadPool.QueueUserWorkItem(MainTestThread);
  25.             ThreadPool.QueueUserWorkItem(Queue1Thread); //启动Queue1线程

  26.             ThreadPool.QueueUserWorkItem(Queue2Thread); //启动Queue2线程

  27.         }

  28.         //测试用的主线程,循环向队列1压入数据。

  29.         public static void MainTestThread(object state)
  30.         {
  31.             Random R = new Random(1);
  32.             double V = 0;

  33.             while (_Exit == false)
  34.             {
  35.                 //在while(true)里一直对数据进行读取,然后放到queue1中,

  36.                 //与此同时如果queue1中有数据,则线程1就开启


  37.                 //随机数

  38.                 V = R.NextDouble();

  39.                 _Queue1.Add(V); //把数据插入到队列1

  40.                 Application.DoEvents();

  41.                 ShowState();

  42.                 Thread.Sleep(100);//生成随机数太快,为了看清效果,暂停n毫秒

  43.             }
  44.         }


  45.         //对queue1中的数据进行处理,处理后放到queue2中

  46.         public static void Queue1Thread(object state)
  47.         {
  48.             while (_Exit == false)
  49.             {
  50.                 while (_Queue1.Count > 0)
  51.                 {
  52.                     //对queue1中的数据进行处理,处理后放到queue2中

  53.                     _Queue2.Add(_Queue1[0]);
  54.                     _Queue1.RemoveAt(0);
  55.                     Application.DoEvents();

  56.                     ShowState();
  57.                 }
  58.             }
  59.         }

  60.         //对queue2中的数据进行处理,处理后放到queue3中

  61.         public static void Queue2Thread(object state)
  62.         {
  63.             while (_Exit == false)
  64.             {
  65.                 while (_Queue2.Count > 0)
  66.                 {
  67.                     //对queue1中的数据进行处理,处理后放到queue2中

  68.                     _Queue3.Add(_Queue2[0]);
  69.                     _Queue2.RemoveAt(0);
  70.                     Application.DoEvents();

  71.                     ShowState();
  72.                 }
  73.             }
  74.         }

  75.         //用于监视各队列状态的线程

  76.         public static void ShowState()
  77.         {
  78.             string stateInfo =
  79.                 QueueTester._Queue1.Count.ToString() + " -> " +
  80.                 QueueTester._Queue2.Count.ToString() + " -> " +
  81.                 QueueTester._Queue3.Count.ToString();

  82.             try
  83.             {
  84.                 if (_OwnerForm != null)
  85.                 {
  86.                     _OwnerForm.Invoke(_StateMethod, stateInfo);
  87.                     Application.DoEvents();
  88.                 }
  89.             }
  90.             catch
  91.             {

  92.             }
  93.         }

  94.     }
窗体代码:见附件
 
阅读(4986) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~