The answer depends on the "work". If work is something that can be safely stopped (i.e. not an I / O blocking operation) - use Backgroundworker.CancelAsync(...)
If you need to cut hard, I would think about using Process , in which case the Aborting process will be cleaner, and process.WaitForExit(timeout) is your friend.
The recommended TPL is great, but unfortunately does not exist in .Net 3.5.
EDIT: You can use Reactive Extensions to follow Ian de Waan's suggestion.
Here is my "action timeout" - this is mostly here so others can comment:
public static bool WaitforExit(this Action act, int timeout) { var cts = new CancellationTokenSource(); var task = Task.Factory.StartNew(act, cts.Token); if (Task.WaitAny(new[] { task }, TimeSpan.FromMilliseconds(timeout)) < 0) { // timeout cts.Cancel(); return false; } else if (task.Exception != null) { // exception cts.Cancel(); throw task.Exception; } return true; }
EDIT : Apparently, this is not exactly what the OP wanted. Here is my attempt to create a cancellable socket receiver:
public static class Ext { public static object RunWithTimeout<T>(Func<T,object> act, int timeout, T obj) where T : IDisposable { object result = null; Thread thread = new Thread(() => { try { result = act(obj); } catch {}
source share