首页 > 编程 > C# > 正文

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

2019-10-29 21:42:00
字体:
来源:转载
供稿:网友

这篇文章主要介绍了C#多线程处理多个队列数据的方法,涉及C#线程与队列的相关操作技巧,需要的朋友可以参考下

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

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. using System.Threading; 
  6. using System.Collections; 
  7. using System.Windows.Forms; 
  8. namespace ThredProcessQueue 
  9. //用于顯示狀態的代理方法類型定義  
  10. public delegate void DelegateShowStateInfo(string state); 
  11. /// <summary>  
  12. /// 測試器  
  13. /// </summary>  
  14. public class QueueTester 
  15. private static bool _Exit = false//標記是否已中斷測試程序  
  16. private static Form _OwnerForm; //測試的窗體  
  17. private static DelegateShowStateInfo _StateMethod; 
  18. private static IList _Queue1 = new ArrayList(); //Queue1的數據  
  19. private static IList _Queue2 = new ArrayList(); //Queue2的數據  
  20. private static IList _Queue3 = new ArrayList(); //Queue3的數據  
  21.  
  22. public static void StopThread() 
  23. _Exit = true
  24. _OwnerForm = null
  25. public static void Testing(Form sender, DelegateShowStateInfo method) 
  26. _StateMethod = method; 
  27. _OwnerForm = sender; 
  28. _Exit = false
  29. ThreadPool.QueueUserWorkItem(MainTestThread); 
  30. ThreadPool.QueueUserWorkItem(Queue1Thread); //啟動Queue1線程  
  31. ThreadPool.QueueUserWorkItem(Queue2Thread); //啟動Queue2線程  
  32. //測試用的主線程,循環向隊列1中壓入數據。  
  33. public static void MainTestThread(object state) 
  34. Random R = new Random(1); 
  35. double V = 0; 
  36. while (_Exit == false
  37. //在while(true)里一直对数据进行读取,然后放到queue1中,  
  38. //与此同时如果queue1中有数据,则线程1就开启  
  39. //臨時數據,隨機數  
  40. V = R.NextDouble(); 
  41. _Queue1.Add(V); //把數據插入到隊列1  
  42. Application.DoEvents(); 
  43. ShowState(); 
  44. Thread.Sleep(100);//生成隨機數太快,為了看清效果,暫停n毫秒  
  45.  
  46. //对queue1中的数据进行处理,处理后放到queue2中  
  47. public static void Queue1Thread(object state) 
  48. while (_Exit == false
  49. while (_Queue1.Count > 0) 
  50. //对queue1中的数据进行处理,处理后放到queue2中  
  51. _Queue2.Add(_Queue1[0]); 
  52. _Queue1.RemoveAt(0); 
  53. Application.DoEvents(); 
  54. ShowState(); 
  55. //对queue2中的数据进行处理,处理后放到queue3中  
  56. public static void Queue2Thread(object state) 
  57. while (_Exit == false
  58. while (_Queue2.Count > 0) 
  59. //对queue1中的数据进行处理,处理后放到queue2中  
  60. _Queue3.Add(_Queue2[0]); 
  61. _Queue2.RemoveAt(0); 
  62. Application.DoEvents(); 
  63. ShowState(); 
  64. //用于監視各隊列狀態的線程  
  65. public static void ShowState() 
  66. string stateInfo = 
  67. QueueTester._Queue1.Count.ToString() " -> " 
  68. QueueTester._Queue2.Count.ToString() " -> " 
  69. QueueTester._Queue3.Count.ToString(); 
  70. try 
  71. if (_OwnerForm != null
  72. _OwnerForm.Invoke(_StateMethod, stateInfo); 
  73. Application.DoEvents(); 
  74. catch 

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表