C#多线程处理多个队列数据的方法
本文实例讲述了C#多线程处理多个队列数据的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Collections;
usingSystem.Windows.Forms;
namespaceThredProcessQueue
{
//用于顯示狀態的代理方法類型定義
publicdelegatevoidDelegateShowStateInfo(stringstate);
///<summary>
///測試器
///</summary>
publicclassQueueTester
{
privatestaticbool_Exit=false;//標記是否已中斷測試程序
privatestaticForm_OwnerForm;//測試的窗體
privatestaticDelegateShowStateInfo_StateMethod;
privatestaticIList_Queue1=newArrayList();//Queue1的數據
privatestaticIList_Queue2=newArrayList();//Queue2的數據
privatestaticIList_Queue3=newArrayList();//Queue3的數據
publicstaticvoidStopThread()
{
_Exit=true;
_OwnerForm=null;
}
publicstaticvoidTesting(Formsender,DelegateShowStateInfomethod)
{
_StateMethod=method;
_OwnerForm=sender;
_Exit=false;
ThreadPool.QueueUserWorkItem(MainTestThread);
ThreadPool.QueueUserWorkItem(Queue1Thread);//啟動Queue1線程
ThreadPool.QueueUserWorkItem(Queue2Thread);//啟動Queue2線程
}
//測試用的主線程,循環向隊列1中壓入數據。
publicstaticvoidMainTestThread(objectstate)
{
RandomR=newRandom(1);
doubleV=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中
publicstaticvoidQueue1Thread(objectstate)
{
while(_Exit==false)
{
while(_Queue1.Count>0)
{
//对queue1中的数据进行处理,处理后放到queue2中
_Queue2.Add(_Queue1[0]);
_Queue1.RemoveAt(0);
Application.DoEvents();
ShowState();
}
}
}
//对queue2中的数据进行处理,处理后放到queue3中
publicstaticvoidQueue2Thread(objectstate)
{
while(_Exit==false)
{
while(_Queue2.Count>0)
{
//对queue1中的数据进行处理,处理后放到queue2中
_Queue3.Add(_Queue2[0]);
_Queue2.RemoveAt(0);
Application.DoEvents();
ShowState();
}
}
}
//用于監視各隊列狀態的線程
publicstaticvoidShowState()
{
stringstateInfo=
QueueTester._Queue1.Count.ToString()"->"
QueueTester._Queue2.Count.ToString()"->"
QueueTester._Queue3.Count.ToString();
try
{
if(_OwnerForm!=null)
{
_OwnerForm.Invoke(_StateMethod,stateInfo);
Application.DoEvents();
}
}
catch
{
}
}
}
}
希望本文所述对大家的C#程序设计有所帮助。