队列之生产者、消费者模式
using System; using System.Threading; using NServiceKit.Redis; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //开启一个线程添加生产者 Thread thread = new Thread(Run); thread.Start(); //开启10个线程来进行消费 Thread[] threads = new Thread[10]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(Pull); threads[i].Start(); } Console.Read(); } //移除队列 消费者 private static void Pull() { IRedisClientFactory factory = RedisClientFactory.Instance; using (IRedisClient client = factory.CreateRedisClient("127.0.0.1", 6379)) { while (true) { if (client.GetListCount("Myqueue") > 0) { string result = client.DequeueItemFromList("Myqueue"); if (string.IsNullOrEmpty(result)) { Thread.SpinWait(1000); } else { Console.WriteLine("Threadid:" + Thread.CurrentThread.ManagedThreadId.ToString() + " " + result); } } else { Thread.SpinWait(1000); } } } } //加入队列 生产者 private static void Run() { IRedisClientFactory factory = RedisClientFactory.Instance; using (IRedisClient client = factory.CreateRedisClient("127.0.0.1", 6379)) { while (true) { Thread.Sleep(3000); client.EnqueueItemOnList("Myqueue", DateTime.Now.ToString()); } } } } }