fork download
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5.  
  6. class Dto {
  7. public int State;
  8. public int Index;
  9. }
  10.  
  11. class Test {
  12. BlockingCollection<Dto> list = new BlockingCollection<Dto>();
  13. public void Run() {
  14. Task.Run(() => backgroundWorker2());
  15. Task.Run(() => backgroundWorker1());
  16. }
  17. void backgroundWorker1() {
  18. for(int i=0; i < 3; i++) {
  19. list.Add(new Dto() { Index = i, State = 2 });
  20. Thread.Sleep(100); // <--------------------------- added
  21. }
  22. }
  23. void backgroundWorker2() {
  24. foreach (var v in list.GetConsumingEnumerable()) {
  25. // сохраняем данные
  26. Console.WriteLine("index=" + v.Index + " state=" + v.State);
  27. // если сохранить не удалось, то возвращаем в list
  28. if (v.Index == 0 && v.State++ < 2) list.Add(v);
  29. if(list.Count == 0)
  30. break;
  31. }
  32. Console.WriteLine("completed");
  33. }
  34. }
  35.  
  36.  
  37. public class Program
  38. {
  39. public static void Main()
  40. {
  41. var t = new Test();
  42. t.Run();
  43. Thread.Sleep(1000); // <----------------- added
  44. }
  45. }
Success #stdin #stdout 0.11s 29080KB
stdin
Standard input is empty
stdout
index=0 state=2
completed