C#多线程处理多个队列数据的方法
时间:2021-03-20 10:00:08|栏目:.NET代码|点击: 次
本文实例讲述了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
{
//用于?@示??B的代理方法?型定?x
public delegate void DelegateShowStateInfo(string state);
/// <summary>
/// ?y?器
/// </summary>
public class QueueTester
{
private static bool _Exit = false; //?擞?是否已中??y?程序
private static Form _OwnerForm; //?y?的窗?w
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?程
}
//?y?用的主?程,循?h向?列1中?喝???。
public static void MainTestThread(object state)
{
Random R = new Random(1);
double V = 0;
while (_Exit == false)
{
//在while(true)里一直对数据进行读取,然后放到queue1中,
//与此同时如果queue1中有数据,则线程1就开启
//?R?r???,?S?C??
V = R.NextDouble();
_Queue1.Add(V); //把???插入到?列1
Application.DoEvents();
ShowState();
Thread.Sleep(100);//生成?S?C?堤?快,?榱丝辞逍Ч?,?和?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();
}
}
}
//用于?O?各?列??B的?程
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#程序设计有所帮助。






