I'm looking for a better way to make a background operation with abort/cancel support. Right now I use this approach:
Task.Factory.StartNew(() => {
var cts = new System.Threading.CancellationTokenSource();
var ct = cts.Token;
try
{
var t = System.Threading.Thread.CurrentThread;
using (ct.Register(t.Abort))
{
LongOperation();
}
}
catch {...} // an exception gets thrown about aborting threads
});
Calling ct.Cancel()
stops the operation even if it's something that cannot usually be interrupted. The focus is that it can be stopped instantly.
I don't think this is unsafe if I'm not doing any file writing. So far it's been working well enough for me, but this code doesn't look proper to me. Is there a more canonical way to start background operations and abort them instantly? Are there any safety concerns I have been lucky not to encounter so far?
Update 2 years later: I looked it all up again, and it seems like a better way to avoid problems is to "abort" a process instead of aborting a thread on your app's main process. See this answer by Eric Lippert. to "What is a safe way to stop a running thread?" question.
Calling ct.Cancel() stops the operation even if it's something that cannot usually be interrupted.
. Furthermore with that cancellation mechanism you have control because it is your responsability to call ThrowIfCancellationRequested on the cancellable method, while with abortion you don't, solving all safety concerns. What would you like to have addressed? \$\endgroup\$