public async Task ConcurrentlyHandleMessages()
{
#region Cancellation AsAbove
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(TimeSpan.FromSeconds(1));
var token = tokenSource.Token;
#endregion
var runningTasks = new ConcurrentDictionary<Task, Task>();
var pumpTask = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
#region Output
"Pumping...".Output();
#endregion
var runningTask = HandleMessage();
runningTasks.TryAdd(runningTask, runningTask);
runningTask.ContinueWith(t =>
{
#region Output
"... done".Output();
#endregion
Task taskToBeRemoved;
runningTasks.TryRemove(t, out taskToBeRemoved);
}, TaskContinuationOptions.ExecuteSynchronously);
}
});
await pumpTask.ConfigureAwait(false);
#region Output
"Pump finished".Output();
#endregion
await Task.WhenAll(runningTasks.Values).ConfigureAwait(false);
#region Output
"All receives finished".Output();
#endregion
tokenSource.Dispose();
}