This is an example from https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library I have tried to execute it in Visual Studio 2022, C#10, Net 6 but exception is not propagated to try catch block. We can emulate some delay to force it to propagate (via sleep, or task.Wait(10), ...) but this is not documented. Is this some kind of compiler optimization or is it bug?
public class Program
{
public static void Main()
{
var task = Task.Run(
() => {
//Thread.Sleep(10); //if uncomment then exception is propagated
throw new CustomException("This exception is expected!");
});
try
{
task.Wait(); //we can use task.Wait(1) then exception is caught
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
{
// Handle the custom exception.
if (ex is CustomException)
{
Console.WriteLine(ex.Message);
}
// Rethrow any other exception.
else
{
throw ex;
}
}
}
}
class CustomException : Exception
{
public CustomException(string s) : base(s) { }
}
}