您的位置:首页 > 编程语言 > C#

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

2015-07-03 10:16 1236 查看

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 线程 队列