乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      C# 并發(fā)隊列ConcurrentQueue

       黃金屋1 2019-05-19

      C# 并發(fā)隊列ConcurrentQueue

      2016年03月08日 21:26:50 conquerwave 閱讀數(shù):17445

      測試函數(shù)

      1. static async Task RunProgram()
      2. {
      3. var taskQueue = new ConcurrentQueue<CustomTask>();
      4. var cts = new CancellationTokenSource();
      5. //生成任務添加至并發(fā)隊列
      6. var taskSource = Task.Run(() => TaskProducer(taskQueue));
      7. //同時啟動四個任務處理隊列中的任務
      8. Task[] processors = new Task[4];
      9. for(int i =1;i <= 4; i++)
      10. {
      11. string processId = i.ToString();
      12. processors[i - 1] = Task.Run(
      13. () => TaskProcessor(taskQueue, "Processor " + processId, cts.Token)
      14. );
      15. }
      16. await taskSource;
      17. //向任務發(fā)送取消信號
      18. cts.CancelAfter(TimeSpan.FromSeconds(2));
      19. await Task.WhenAll(processors);
      20. }

      產(chǎn)生任務
      1. static async Task TaskProducer(ConcurrentQueue<CustomTask> queue)
      2. {
      3. for(int i= 0;i < 20; i++)
      4. {
      5. await Task.Delay(50);
      6. var workItem = new CustomTask { Id = i };
      7. queue.Enqueue(workItem);
      8. Console.WriteLine("task {0} has been posted", workItem.Id);
      9. }
      10. }

      執(zhí)行任務
      1. static async Task TaskProcessor(ConcurrentQueue<CustomTask> queue, string name, CancellationToken token)
      2. {
      3. CustomTask workItem;
      4. bool dequeueSuccesful = false;
      5. await GetRandomDelay();
      6. do
      7. {
      8. dequeueSuccesful = queue.TryDequeue(out workItem);
      9. if (dequeueSuccesful)
      10. {
      11. Console.WriteLine("task {0} has been processed by {1}", workItem.Id, name);
      12. }
      13. await GetRandomDelay();
      14. }
      15. while (!token.IsCancellationRequested);
      16. }

      1. static Task GetRandomDelay()
      2. {
      3. int delay = new Random(DateTime.Now.Millisecond).Next(1500);
      4. return Task.Delay(delay);
      5. }
      1. class CustomTask
      2. {
      3. public int Id { get; set; }
      4. }

      調用
      1. static void Main(string[] args)
      2. {
      3. Task t = RunProgram();
      4. t.Wait();
      5. Console.ReadKey();
      6. }

        本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,請點擊一鍵舉報。
        轉藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多