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

时间:2021-05-20

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章