private async Task RunWorkerAsync () { //Pull the cancellation token CancellationToken stopToken = mStopTokenSource .Token; //Check for cancellation before we start // the processing loop if ( stopToken.IsCancellationRequested ) return; while ( true ) { try { //Check for cancellation at the beginning // of processing each loop stopToken.ThrowIfCancellationRequested(); //Check if buffer can deliver new tasks to us. // If not (and it's permanent), break worker processing loop. if ( !await PerformBufferCheckAsync() ) break; //It may be that the wait handle was signaled // as part of the Stop operation, // so we need to check for that as well. stopToken.ThrowIfCancellationRequested(); //Finally, dequeue and execute the task // and forward the result to the result queue IQueuedTaskToken queuedTaskToken = mTaskBuffer.TryGetNextTask(); if ( queuedTaskToken != null ) await ExecuteAndProcessResultAsync( queuedTaskToken, stopToken ); else mLogger.Debug( "Nothing to execute: no task was retrieved." ); //At the end of the loop, reset the handle mWaitForClearToFetchTask.Reset(); } catch ( OperationCanceledException ) { mLogger.Debug( "Worker stop requested. Breaking processing loop..." ); break; } } }
public void ConsumeBuffer() { mConsumeBufferTask = Task.Run(() => { while (!mTaskBuffer.IsCompleted) { IQueuedTaskToken queuedTaskToken = mTaskBuffer.TryGetNextTask(); if (queuedTaskToken != null) { mConsumedTasks.Add(queuedTaskToken); } else { Task.Delay(10).Wait(); } } }); }