Created
September 6, 2012 23:16
-
-
Save oising/3661177 to your computer and use it in GitHub Desktop.
Sample cancellation of ThreadAbortException with Thread.ResetAbort
This file contains hidden or 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
internal class CodeBlockWithTimeout<TResult> | |
{ | |
private readonly Func<TResult> _block; | |
private readonly string _name; | |
private CodeBlockWithTimeout(Func<TResult> block, string name) | |
{ | |
this._block = block; | |
_name = name; | |
} | |
internal static CodeBlockWithTimeout<TResult> Create(Action block, string name = "anonymous") | |
{ | |
return Create(() => | |
{ | |
block(); | |
return default(TResult); | |
}, name); | |
} | |
internal static CodeBlockWithTimeout<TResult> Create(Func<TResult> block, string name = "anonymous") | |
{ | |
return new CodeBlockWithTimeout<TResult>(block, name); | |
} | |
internal TResult TryInvoke(TimeSpan timeout) | |
{ | |
TResult result = default (TResult); | |
var runner = new Thread( | |
() => | |
{ | |
try | |
{ | |
result = this._block.Invoke(); | |
} | |
catch (ThreadAbortException) | |
{ | |
Tracer.LogWarning("CodeBlockWithTimeout '{0}': ResetAbort()", _name); | |
Thread.ResetAbort(); | |
} | |
}) { IsBackground = true }; | |
runner.Start(); | |
// wait for thread to terminate naturally, or until timeout hit | |
if (!runner.Join(timeout)) | |
{ | |
Tracer.LogError("CodeBlockWithTimeout '{0}': Timeout expired - trying to abort thread. ", _name); | |
// timed out, signal to abort the thread | |
runner.Abort(); | |
throw new TimeoutException( | |
String.Format("Code block '{0}' timed out.", _name)); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this for a previous project to enable timeout functionality for complex Regexes using NET35. Regex Timeouts were only added to the BCL in 4.5. An example use would be:
Make sense?