using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConcurrentMakeTest { class Program { public static BlockingCollection<string> m_Queue = new BlockingCollection<string>(); public static Object obj = new Object(); static void Main(string[] args) { Task producer = Task.Run(() => Producer()); Task consumer1 = Consumer(); Task consumer2 = Consumer(); Task consumer3 = Consumer(); Task consumer4 = Consumer(); Task.WaitAll(producer, consumer1, consumer2, consumer3, consumer4); Console.WriteLine("-----------------------------------------"); Console.ReadLine(); } static void Producer() { try { for (int i = 0; i <= 10; i++) { m_Queue.TryAdd(i.ToString()); } } finally { m_Queue.CompleteAdding(); Console.WriteLine("There are totally {0} items in the queue.\n", m_Queue.Count); Thread.Sleep(500); } } static async Task Consumer() { try { while (m_Queue.Count > 0) { string x = ""; m_Queue.TryTake(out x); await Task.Factory.StartNew(() => { lock (obj) { PrintItem m = new PrintItem(DateTime.Now); m.RunScript(x); } }); } } catch (Exception ex) { Console.Write("Exception: " + ex.Message + "\r\n" + ex.StackTrace); } } } }
public class PrintItem { public PrintItem(DateTime t) { Console.WriteLine(t); } internal void RunScript(string item) { Console.WriteLine(item); } }
obj
RunScript(x)
lock
<a href="https://www.flickr.com/photos/67801243@N06/15528088831/">this image</a>
N
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)