How to make asynchronous methods that use a stream thread in a queue

I have a service that ensures that one popup is displayed at a time. AddPopupAsync can be called at the same time, that is, a popup window is open, while the other 10 AddPopupAsync requests drop out. The code:

 public async Task<int> AddPopupAsync(Message message) { //[...] while (popupQueue.Count != 0) { await popupQueue.Peek(); } return await Popup(interaction); } 

But I can notice two unwanted things that can happen due to the lack of thread safety :

  • If the queue is empty, Peek will throw an exception
  • If thread A is unloaded before the first statement in Popup, another thread B will not wait for the popup A to wait, because the queue is still empty.

The popup method works with TaskCompletionSource and before calling its SetResult method, popupQueue.Dequeue() called.

I am thinking of using the atomic TryPeek from ConcurrentQueue to make thread # 1 safe:

 do { Task<int> result; bool success = popupQueue.TryPeek(out result); if (!success) break; await result; } while (true); 

Then I read about AsyncProducerConsumerCollection , but I'm not sure if this is the easiest solution.

How can I ensure thread safety in a simple way? Thanks.

+5
source share
1 answer

To just add thread safety, you should use ConcurrentQueue . This is a thread-safe implementation of a queue, and you can use it just as if you were using a queue without worrying about concurrency.

However, if you need a queue, you can await asynchronously (which means that you are not busy or expect a thread lock), you should use the TPL Dataflow BufferBlock , which is very similar to the AsyncProducerConsumerCollection already implemented for you:

 var buffer = new BufferBlock<int>(); await buffer.SendAsync(3); // Instead of enqueue. int item = await buffer.ReceiveAsync(); // instead of dequeue. 

ConcurrentQueue great for preventing threads, but wastefully with high levels of competition. BufferBlock not only thread safe, it also gives you asynchronous coordination (usually between consumer and producer).

+8
source

Source: https://habr.com/ru/post/1207588/


All Articles