二、 使用ConcurrentQueue来实现异步处理
本示例将学习如何创建一个能被多个线程异步处理的一组任务的例子。
一、程序示例代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading; namespace ThreadCollectionDemo { class Program { const string item = "Dict Name"; public static string CurrentItem; static double time1; static void Main(string[] args) { Console.WriteLine(string.Format("----- ConcurrentQueue 操作----")); Task task = TaskRun1(); task.Wait(); Console.Read(); } private static async Task TaskRun1() { var queue = new ConcurrentQueue<CustomTask>(); var cts = new CancellationTokenSource(); var taskSrc = Task.Run(() => TaskProduct(queue)); Task[] process = new Task[4]; for (int i = 1; i <= 4; i++) { string processId = i.ToString(); process[i - 1] = Task.Run(() => TaskProcess(queue, "Processer " + processId, cts.Token)); } await taskSrc; cts.CancelAfter(TimeSpan.FromSeconds(2)); await Task.WhenAll(process); } static async Task TaskProduct(ConcurrentQueue<CustomTask> queue) { for (int i = 0; i < 20; i++) { await Task.Delay(50); var workitem = new CustomTask { Id = i }; queue.Enqueue(workitem); Console.WriteLine(string.Format("把{0} 元素添加到ConcurrentQueue",workitem.Id)); } } static async Task TaskProcess(ConcurrentQueue<CustomTask> queue,string name,CancellationToken token) { CustomTask workitem; bool dequeueSuccesfl = false; await GetRandomDely(); do { dequeueSuccesfl = queue.TryDequeue(out workitem); if (dequeueSuccesfl) { Console.WriteLine(string.Format("元素 {0} 从ConcurrentQueue中取出 ,名称:{1} ", workitem.Id, name)); } await GetRandomDely(); } while (!token.IsCancellationRequested); } static Task GetRandomDely() { int dely = new Random(DateTime.Now.Millisecond).Next(1, 1000); return Task.Delay(dely); } } public class CustomTask { public int Id { get; set; } } }