I am new to Tasks in C# and I have come across an issue I don't under stand. In the following code can someone please explain why the WriteLine at the end of the Unsubscribe Method never gets called. It seems to be related to ContinueWith in the preceding foreach loop as if I comment that out it works fine. Thanks
using System;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
Task.Run(() => Unsubscribe());
Console.WriteLine("Method: Main. End");
Console.ReadKey();
}
private static void Unsubscribe()
{
Dictionary<int, string> dicPairsBySubID = new Dictionary<int, string>();
dicPairsBySubID.Add(1, "A");
dicPairsBySubID.Add(2, "B");
dicPairsBySubID.Add(3, "C");
dicPairsBySubID.Add(4, "D");
dicPairsBySubID.Add(5, "E");
List<Task> taskList = new List<Task>();
foreach (KeyValuePair<int, string> sub in dicPairsBySubID)
{
int chanID = sub.Key;
Task task = Task.Run(() => SendUnsubscribe(chanID))
.ContinueWith(tsk =>
{
var flattened = tsk.Exception.Flatten();
flattened.Handle(ex =>
{
Console.WriteLine(string.Format("Error unsubscribing pair {0} (chanID = {2})", sub.Value, chanID), ex);
return true;
});
}, TaskContinuationOptions.OnlyOnFaulted);
taskList.Add(task);
}
Task.WhenAll(taskList).Wait();
// WHY DOES THIS NEVER GET RUN?
Console.WriteLine("Method: Unsubscribe. End");
}
private static async Task SendUnsubscribe(int chanID)
{
await SendAsync(chanID);
Console.WriteLine("Method: SendUnsubscribe. Chan ID: " + chanID);
}
private static async Task SendAsync(int chanID)
{
await Task.Run(() => Thread.Sleep(1000));
Console.WriteLine("Method: SendAsync. Chan ID: " + chanID);
}
}