Before .NET 4.0, my understanding is that if one wanted to start a thread to do some work which could be cancelled, one would start a
BackgroundWorker. .NET 4 brought about the TAP model, and a whole bunch of new async and threading stuff. Is the
BackgroundWorker still the way to do it?
Best How To :
async (and the corollary keyword
await) are both .NET 4.5, and not available in 4.0. If you want to use
Tasks at all, I highly recommend upgrading to .NET 4.5. Even in 4.0, however, there areseveral overloaded methods which optionally take
CancellationTokens that can be used to cancel running work.
EDIT: As pointed out in comments, there are ways to get
await on .NET 4.0 - you just need less work and have more library support in 4.5. Not something I would recommend without a dire need for XP support.
As of .NET 4.5, the
BackgroundWorker class is not marked as
[Obsolete], so there's no reason you shouldn't continue using it directly.
Thread class contains a direct
.Abort() method, which can be used to create a worker which can be cancelled. Note that this abort happens via throwing a
ThreadAbortException in the running thread, thus allowing a
catch statement to still perform any cleanup in the event of thread abortion.