Created
February 18, 2016 14:31
-
-
Save negativeeddy/df6dc61c3ac2c5f7dc36 to your computer and use it in GitHub Desktop.
The is a simple c# console app that demonstrates various behaviors when .NET Tasks do or do not have their exceptions observed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace UnobservedExceptions | |
{ | |
// NOTES: | |
// 1) run this in a 4.5 app and watch the behavior differences when changing the | |
// ThrowUnobservedTaskExceptions config option | |
// <configuration> | |
// <startup> | |
// <supportedRuntime version = "v4.0" sku=".NETFramework,Version=v4.5.2" /> | |
// </startup> | |
// <runtime> | |
// <ThrowUnobservedTaskExceptions enabled = "true" /> | |
// </ runtime > | |
// </ configuration > | |
// | |
// 2) Run this in RELEASE mode not DEBUG mode | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Options:"); | |
Console.WriteLine("1 - Don't observe, don't collect"); | |
Console.WriteLine("2 - Don't observe, do collect"); | |
Console.WriteLine("3 - do observe, don't collect"); | |
Console.WriteLine("4 - do observe, do collect"); | |
string cmd = Console.ReadLine(); | |
switch(cmd) | |
{ | |
case "1": | |
RunTest(false, false); | |
break; | |
case "2": | |
RunTest(false, true); | |
break; | |
case "3": | |
RunTest(true, false); | |
break; | |
case "4": | |
RunTest(true, true); | |
break; | |
} | |
} | |
private static void RunTest(bool observe, bool collect) | |
{ | |
Console.WriteLine($"Observe:{observe}, Collect:{collect}"); | |
Task t = Task.Run(() => | |
{ | |
Console.WriteLine("Throwing!"); | |
throw new NotImplementedException("Cant do that!"); | |
}); | |
Thread.Sleep(100); // wait here to let the task get scheduled and run | |
if (observe && t.Exception != null) | |
{ | |
Console.WriteLine($"Found an exception! {t.Exception.Message}"); | |
} | |
if (collect) | |
{ | |
// force a garbage collection and the Task finalizers to run | |
Console.WriteLine("Press enter to collect"); | |
Console.ReadLine(); | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
} | |
Console.WriteLine("Finished"); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment