This question is an exact duplicate:

there is a method, I have been wondering for the third day how to remake it under .net3.5. Libraries cannot be used. Or another solution may be needed here.

ConcurrentQueue<KeyValuePair<int, byte[]>> queue_block = new ConcurrentQueue<KeyValuePair<int, byte[]>>(); public static void ADD_Block_to_Queue(Queue<KeyValuePair<int,byte[]>> queue_block,Stream fs) { foreach (KeyValuePair<int, byte[]> block in Read_Blockk(fs)) { queue_block.Enqueue(block); while (queue_block.Count > 100) { var t = Task.Run(async delegate { await Task.Delay(1000); return 42; }); t.Wait(); } } } 

Reported as a duplicate by Pavel Mayorov c # Aug 2 '18 at 12:24 pm

This question has been marked as a duplicate of an existing one.

  • so what does not work? - tym32167
  • 3
    Tell me, and when you pass the interview - will you also upload your work to this site? - Pavel Mayorov
  • one
    @VladimrVladimirovoch no, you can not. Because Queue is a thread-safe collection, and without external synchronization another thread should not have access to it while you are reading the file. - Pavel Mayorov
  • one
    @VladimrVladimirovoch and you need to use any thread-safe queue. In .net 4.0 it is BlockingCollection, and in .net 3.5 you have to write it yourself. - Pavel Mayorov
  • one
    @VladimrVladimirovoch yes. And I also want to say that the thread-safe queue is often called the Producer-Consumer pattern. - Pavel Mayorov

1 answer 1

Since the task does nothing and is expected to be synchronous, it can be replaced with

 public static void ADD_Block_to_Queue(Queue<KeyValuePair<int, byte[]>> queue_block, Stream fs) { foreach (KeyValuePair<int, byte[]> block in Read_Blockk(fs)) { queue_block.Enqueue(block); while (queue_block.Count > 100) { Thread.Sleep(1000); } } }