等待两个任务完成然后打印sonething [英] Wait two task completes then print sonething

查看:110
本文介绍了等待两个任务完成然后打印sonething的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个完成生产者 - 消费者模式的任务。

I have two tasks which complete producer-consumer pattern.

using (Task t1 = Task.Factory.StartNew(() =>
                          {
                              if (list.Count > 0)
                                  Console.WriteLine("Block begin");
                              for (int i = 0; i < 4; i++)
                              {
                                  if (list.Count > 0)
                                  {
                                      var firstItem = list.FirstOrDefault();
                                    // blah blah
                                      list.Remove(firstItem);
                                  }
                              }
                              bc.CompleteAdding();
                          }
                               ))

                       using (Task t2 = Task.Factory.StartNew(() =>
                           // blah blah))
                           Task.WaitAll(t1, t2);
                           Console.WriteLine("Block end");



预期输出应该如下:


The expected output should like:

Block begin
item 1
item 2
...
Block end



但有时我得到了


But sometimes I got

Block begin
Block end
item 1
item 2
...



如何达到预期效果?


How to achieve the expected result?

推荐答案

尝试删除使用 来自任务。我从未在使用声明中添加任务。
Try removing the "usings" from the Tasks. I've never put a task in a using statement.


这篇关于等待两个任务完成然后打印sonething的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆