How to correctly clean up after long running task is cancelled

后端 未结 1 632
傲寒
傲寒 2021-01-03 00:41

I\'ve created a class whose purpose is to abstract away the control of concurrent access to a queue.

The class is designed to be instantiated on a single thread, wri

相关标签:
1条回答
  • 2021-01-03 01:18

    Careful programming is the only thing that's gonna cut it. Even if you cancel the operation you might have a pending operation that's not completing in a fashionable amount of time. It could very well be a blocking operation that's deadlocked. In this case your program will not actually terminate.

    For instance, if I call your CleanUp method several times or without calling Start first I'm getting the feeling it's going to crash.

    A 2 seconds timeout during cleanup, feels more arbitrary than planned, and I'd actually go as far as to ensure that things shutdown properly or crash/hang (you never want to leave concurrent stuff in an unknown state).

    Also, the IsRunning is explicitly set, not inferred from the state of the object.

    For inspiration I'd like you to look at a similar class I wrote recently, it's a producer/consumer pattern that does it's work in a background thread. You can find that source code on CodePlex. Though, this was engineered to solve a very specific problem.

    Here, cancellation is solved by enquing a specific type that only the worker thread recognizes and thus begins shutting down. This also ensures that I never cancel pending work, only whole units of work are considered.

    To improve this situation a bit you can have a separate timer for current work and abort or rollback incomplete work if it's canceled. Now, implementing a transaction like behavior is going to take some trial and error because you need to look at every possible corner case and ask yourself, what happens if the program crashes here? Ideally all these code paths so lead to a recoverable or known state from which you can resume your work. But as I think you've guessed already, that's going to take careful programming and a lot of testing.

    0 讨论(0)
提交回复
热议问题