当前位置: 移动技术网 > IT编程>开发语言>c# > C#多线程处理多个队列数据的方法

C#多线程处理多个队列数据的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#多线程处理多个队列数据的方法。分享给大家供大家参考。具体实现方法如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
using system.collections;
using system.windows.forms;
namespace thredprocessqueue
{
  //用于顯示狀態的代理方法類型定義 
  public delegate void delegateshowstateinfo(string state);
  /// <summary> 
  /// 測試器 
  /// </summary> 
  public class queuetester
  {
   private static bool _exit = false; //標記是否已中斷測試程序 
   private static form _ownerform; //測試的窗體 
   private static delegateshowstateinfo _statemethod;
   private static ilist _queue1 = new arraylist(); //queue1的數據 
   private static ilist _queue2 = new arraylist(); //queue2的數據 
   private static ilist _queue3 = new arraylist(); //queue3的數據 
   
   public static void stopthread()
   {
     _exit = true;
     _ownerform = null;
   }
   public static void testing(form sender, delegateshowstateinfo method)
   {
     _statemethod = method;
     _ownerform = sender;
     _exit = false;
     threadpool.queueuserworkitem(maintestthread);
     threadpool.queueuserworkitem(queue1thread); //啟動queue1線程 
     threadpool.queueuserworkitem(queue2thread); //啟動queue2線程 
   }
   //測試用的主線程,循環向隊列1中壓入數據。 
   public static void maintestthread(object state)
   {
     random r = new random(1);
     double v = 0;
     while (_exit == false)
     {
      //在while(true)里一直对数据进行读取,然后放到queue1中, 
      //与此同时如果queue1中有数据,则线程1就开启 
      //臨時數據,隨機數 
      v = r.nextdouble();
      _queue1.add(v); //把數據插入到隊列1 
      application.doevents();
      showstate();
      thread.sleep(100);//生成隨機數太快,為了看清效果,暫停n毫秒 
     }
   }
   
   //对queue1中的数据进行处理,处理后放到queue2中 
   public static void queue1thread(object state)
   {
     while (_exit == false)
     {
      while (_queue1.count > 0)
      {
        //对queue1中的数据进行处理,处理后放到queue2中 
        _queue2.add(_queue1[0]);
        _queue1.removeat(0);
        application.doevents();
        showstate();
      }
     }
   }
   //对queue2中的数据进行处理,处理后放到queue3中 
   public static void queue2thread(object state)
   {
     while (_exit == false)
     {
      while (_queue2.count > 0)
      {
        //对queue1中的数据进行处理,处理后放到queue2中 
        _queue3.add(_queue2[0]);
        _queue2.removeat(0);
        application.doevents();
        showstate();
      }
     }
   }
   //用于監視各隊列狀態的線程 
   public static void showstate()
   {
     string stateinfo =
     queuetester._queue1.count.tostring() " -> "
     queuetester._queue2.count.tostring() " -> "
     queuetester._queue3.count.tostring();
     try
     {
      if (_ownerform != null)
      {
        _ownerform.invoke(_statemethod, stateinfo);
        application.doevents();
      }
     }
     catch
     {
     }
   }
  }
}

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网