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) {
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.
source share