简单消息队列
来源:互联网 发布:微博旅游博主数据统计 编辑:程序博客网 时间:2024/04/30 03:05
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace TestApplication
{
/// <summary>
/// 消息队列
/// </summary>
/// <typeparam name="T"></typeparam>
public class MessageQueue<T>
{
private static object _lockObj = new object();
private static MessageQueue<T> _instance;
private Queue<T> _msgQueue;
private MessageQueue()
{
this._msgQueue = new Queue<T>();
}
public static MessageQueue<T> CreateInstance()
{
if (_instance == null)
{
lock (_lockObj)
{
if (_instance == null)
{
_instance = new MessageQueue<T>();
}
}
}
return _instance;
}
public void PushMessage(T message)
{
lock (_lockObj)
{
if (_msgQueue.Contains(message))
return;
_msgQueue.Enqueue(message);
}
}
public bool IsEmpty()
{
return _msgQueue.Count < 1;
}
public T GetMessage()
{
lock (_lockObj)
{
if (_msgQueue.Count > 0)
return _msgQueue.Dequeue();
else
return default(T);
}
}
}
public class MessagePump<T>
{
public Action<T> DoAction;
private static object _lockObj = new object();
private static MessagePump<T> _instance;
public static MessagePump<T> CreateInstance()
{
if (_instance == null)
{
lock (_lockObj)
{
if (_instance == null)
{
_instance = new MessagePump<T>();
}
}
}
return _instance;
}
public MessageQueue<T> Messages { get; set; }
public bool IsWorking { get; private set; }
public void DoWork()
{
T empty = default(T);
while (!Messages.IsEmpty())
{
IsWorking = true;
var item = Messages.GetMessage();
if (item.Equals(empty))
{
break;
}
if (DoAction != null)
DoAction(item);
}
IsWorking = false;
}
}
}
调用
private void button1_Click(object sender, EventArgs e)
{
MessageQueue<int> messages = MessageQueue<int>.CreateInstance();
MessagePump<int> pump = MessagePump<int>.CreateInstance();
pump.Messages = messages;
pump.DoAction = new Action<int>((item) =>
{
this.Invoke(new Action(() =>
{
listBox1.Items.Add(item);
}));
// 模拟处理失败,重新入队
if (item % 2 == 0)
{
messages.PushMessage(item + 1);
if (!pump.IsWorking)
pump.DoWork();
}
}
);
List<Thread> threads = new List<Thread>();
for (var i = 1; i <= 10; i++)
{
int j = i;
threads.Add(new Thread(() =>
{
messages.PushMessage(j);
if (!pump.IsWorking)
pump.DoWork();
}));
}
for(var i = 0; i < threads.Count; i++)
{
threads[i].Start();
}
}
- 简单消息队列
- linux 消息队列简单例程
- 消息队列的简单处理
- linux 消息队列简单入门
- RocketMQ 消息队列简单部署
- Redis实现简单消息队列
- 简单的消息队列实例
- 消息队列的简单实现
- Redis实现简单消息队列
- RocketMQ 消息队列简单部署
- redis简单的消息队列
- Redis实现简单消息队列
- Redis实现简单消息队列
- IPC简单介绍(一)消息队列
- 一个简单的C#消息队列示例
- ActiveMQ的最简单应用-队列消息
- 【进程通信】消息队列简单例子
- 一个简单的C#消息队列示例
- INT 10H中断
- eclipse常用调试快捷键
- MFC学习笔记——如何使窗口最大化,但不遮盖任务栏
- django Model 继承
- 安卓的访问网络
- 简单消息队列
- 9号中断与10号中断......
- Codeforces Round #206 (Div. 2)
- POJ3624Charm Bracelet,用到了滚动数组(AC)
- SQL语句中where 1=1的作用(正解)
- SpringMVC 基础配置
- Eclipse J2EE Maven 配置
- 利用opencv寻找乒乓球的坐标及大小
- 问一个低级问题:头文件包含#include有何作用与意义?