Today I was confronted with a interesting case of Task‘s behavior. Below you can see the minimal example. Can you determine, without running the code, what would be the output of the following code?

static void Main(string[] args)
{
  Task.Run(() => Console.WriteLine("Main part"))
   .ContinueWith(t =>
       Console.WriteLine("OnFaulted!"),
     TaskContinuationOptions.OnlyOnFaulted)
   .ContinueWith(t =>
       Console.WriteLine("OnCanceled!"),
     TaskContinuationOptions.OnlyOnCanceled);
   
   Console.ReadLine();
}

If not, run it and while seeing the output – can you explain why this is happening? I think it’s a good interview question. It can verify if one knows their TPL 😉
When you understand what’s going on, it’s quite obvious why this is the result but I was scratching my head today for a while.

I’ll post the answer in a few days so you can try to analyze this issue for your own.