<p>In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch <code>ThreadAbortedException</code>, do <code>Thread.ResetAbort()</code> and die beautifully (that is, the thread).</p>

<p>The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner:</p>

<pre><code>try {
} finally {
  // vital code
}
</code></pre>

<p>However, I didn't find any other solution.</p>

<p>Is this another way to delay the interference of <code>ThreadAbortException</code> until the end of the block?</p>

[{'answer_id': 47147, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 3, 'selected': True, 'text': "<p>The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why you are using ThreadAbortExceptions at all.</p>\n\n<p>A better pattern would be to simply use a flag to indicate to the running thread that it should abort, and then test the flag regularly while it is working.  If it is set you can throw an exception at that point if you want.</p>\n\n<p>With this pattern you are totally in control of when the thread will act on the abort, and don't have to worry about the critical operations being interrupted.</p>\n"}, {'answer_id': 47150, 'author': 'Corey', 'author_id': 1595, 'author_profile': 'https://Stackoverflow.com/users/1595', 'pm_score': 2, 'selected': False, 'text': '<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.begincriticalregion.aspx" rel="nofollow noreferrer">Thread.BeginCriticalRegion()</a> </p>\n\n<blockquote>\n  <p>Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. </p>\n</blockquote>\n\n<pre><code>Thread.BeginCriticalRegion()\n\n//do important stuff here\n\nThread.EndCriticalRegion()\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/47144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4850/']