Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two tasks which complete producer-consumer pattern.
C#
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
C#
Block begin
Block end
item 1
item 2
...

How to achieve the expected result?
Posted
Comments
Richard Deeming 11-Aug-14 15:01pm    
You've removed too much of the important code to get a sensible answer to this question.

* What type is list? Is it thread-safe? Is it accessed from multiple threads?
* What type is bc?
* What code did you replace with the "blah blah" comments?

1 solution

Try removing the "usings" from the Tasks. I've never put a task in a using statement.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900