用于线程同步传递数据的队列
核心对象:
代码
1 public class MessageQueue<T>
2 {
3 private Object _asynO = new Object();
4 private Queue<T> _queue = new Queue<T>();
5 private ManualResetEvent _asynEvent = new ManualResetEvent(true);
6
7 public T Dequeue(){
8 T t = default(T);
9 if (_queue.Count <= 0)
10 {
11 _asynEvent.Reset();
12 _asynEvent.WaitOne();
13 }
14
15 lock (_asynO)
16 {
17 t = _queue.Dequeue();
18 }
19 return t;
20 }
21
22 public void Enqueue(T t) {
23 lock (_asynO)
24 {
25 _queue.Enqueue(t);
26 _asynEvent.Set();
27 }
28 }
29 }
2 {
3 private Object _asynO = new Object();
4 private Queue<T> _queue = new Queue<T>();
5 private ManualResetEvent _asynEvent = new ManualResetEvent(true);
6
7 public T Dequeue(){
8 T t = default(T);
9 if (_queue.Count <= 0)
10 {
11 _asynEvent.Reset();
12 _asynEvent.WaitOne();
13 }
14
15 lock (_asynO)
16 {
17 t = _queue.Dequeue();
18 }
19 return t;
20 }
21
22 public void Enqueue(T t) {
23 lock (_asynO)
24 {
25 _queue.Enqueue(t);
26 _asynEvent.Set();
27 }
28 }
29 }
调用实例
代码
1 class Program
2 {
3 static MessageQueue<string> mqStr = new MessageQueue<string>();
4
5 static void Main(string[] args)
6 {
7 Thread t = new Thread(ThreadMethod);
8 t.Start();
9 while (true) {
10 Console.WriteLine("请输入:");
11 string str = Console.ReadLine();
12 mqStr.Enqueue(str);
13 }
14 }
15
16 static void ThreadMethod() {
17 int i = 0;
18 while (true) {
19 Console.WriteLine(mqStr.Dequeue() + ":" + i++.ToString());
20 }
21 }
22 }
2 {
3 static MessageQueue<string> mqStr = new MessageQueue<string>();
4
5 static void Main(string[] args)
6 {
7 Thread t = new Thread(ThreadMethod);
8 t.Start();
9 while (true) {
10 Console.WriteLine("请输入:");
11 string str = Console.ReadLine();
12 mqStr.Enqueue(str);
13 }
14 }
15
16 static void ThreadMethod() {
17 int i = 0;
18 while (true) {
19 Console.WriteLine(mqStr.Dequeue() + ":" + i++.ToString());
20 }
21 }
22 }