I have a Queue
that needs to try to process when anything updates in it (add, remove or update).
However, I don't want any of the callers to wait while the processing is happening (either for the processing to happen or while the processing is happening).
This is what I came up with:
private static readonly SemaphoreSlim asyncLock = new SemaphoreSlim(1);
private async void ProcessQueue()
{
// Lock this up so that one thread at a time can get through here.
// Others will do an async await until it is their turn.
await asyncLock.WaitAsync();
try
{
// Offload this to a background thread (so that the UI is not affected)
var queueProcessingTask = Task.Run( () =>
{
var processingStuck = false;
while (myQueue.Count >= 1 && !processingStuck)
{
// Get the next item
var queueItem = myQueue.Peek();
// Try to process this one. (ie DoStuff)
processingStuck = ProcessQueueItem(queueItem);
// If we processed successfully, then we can dequeue the item
if (!processingStuck)
myQueue.Dequeue();
}
});
Task.WaitAll(queueProcessingTask);
}
finally
{
asyncLock.Release();
}
}
Is my Thread and async handling going to ensure that only 1 queueItem at a time can ever be "in the works"?
And will this avoid using resources from the UI thread?