Skip to content

Instantly share code, notes, and snippets.

@oising
Created September 6, 2012 23:16
Show Gist options
  • Save oising/3661177 to your computer and use it in GitHub Desktop.
Save oising/3661177 to your computer and use it in GitHub Desktop.
Sample cancellation of ThreadAbortException with Thread.ResetAbort
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;
}
}
@oising
Copy link
Author

oising commented Sep 6, 2012

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:

            string parsed =
                CodeBlockWithTimeout<string>.Create(() => StripVMLFromHTML(raw, options), "Stripping VML")
                    .TryInvoke(TimeSpan.FromSeconds(10));

Make sense?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment