title: How to save a dump, including local variables, after an unhandled exception occurs in TPL?
body: <p>My idea of handling exceptions is as follows.</p>
  
  <p>When an unhandled exception occurs, I want to save a dump with full memory, including local variables available at the line where the exception happened. Then I can analyze that dump and either prevent the exception from happening again or handle it with <code>try</code>...<code>catch</code>.</p>
  
  <p>I almost achieved my goal by simply handling <code>AppDomain.CurrentDomain.UnhandledException</code> event. It fires every time an unhandled exception occurs and its call stack includes the line of the exception, so after saving a dump I have all the data I need including local variables.</p>
  
  <p>However, that solution doesn't work with TPL. After encountering an unhandled exception a task terminates and only then allows me to access the exception through various means (checking <code>Task.Exception</code>, handling <code>TaskScheduler.UnobservedTaskException</code> event, using continuation with <code>TaskContinuationOptions.OnlyOnFaulted</code>, using <code>Task.Wait()</code> or <code>await</code>...). Those methods obviously do not allow me to include local variables from within a task, since the task itself already terminated.</p>
  
  <p>Is there something I can do to catch unhandled exceptions occuring within tasks before those tasks are terminated? And if so, can I then save a dump including local variables from within those tasks?</p>
  
  <p>Here are some ideas for a solution I came up with:</p>
  
  <ol>
  <li>I can use <code>AppDomain.CurrentDomain.FirstChanceException</code>, but from within that event I can't check whether an exception will be handled in a <code>catch</code> block or not. And obviously I don't want to save a dump for some exception that will be later handled in a <code>catch</code> block. But, since it looks like the event handles only one <code>AppDomain</code>, I could theoretically run all the code placed within <code>try</code>...<code>catch</code> blocks from some other <code>AppDomain</code>. But I have no idea how to achieve that nor whether it would actually work, not to mention possible drawbacks.</li>
  <li>Is it possible to write an alternative to <code>try</code>...<code>catch</code> in IL, which won't leave the <code>try</code> block after encountering an exception, thus allowing access to local variables?</li>
  <li>I can simply use <code>try</code>...<code>catch</code> and declare my local variables before the <code>try</code> block, but I treat that solution as the last resort, since it's ugly.</li>
  </ol>