How to handle the problem of missing checking of ctsToken in too many places in a C# program with a stop button? #101756
Replies: 2 comments 6 replies
-
What kind of tasks are you doing? Long-running tasks can roughly be categorized as computation or I/O. For computational tasks like graphic processing, you need to check for cancellation yourself, but only at the core worker which is most expensive. It typically loops for some times and check for cancellation once, to avoid excessive overhead. For I/O tasks like file and network, most of the time is spent on waiting for the resource to be available. You need to pass the cancellation token to corresponding I/O method. The operating system will listen the cancellation for you when doing I/O job. In both situations, you shouldn't check for cancellation anywhere, but only at the methods that takes most of the time.
There isn't such a way. Cancelling a method that's not aware of the cancellation is very dangerous and can leave many things in unpredicatable state. That's why |
Beta Was this translation helpful? Give feedback.
-
There's CA2016 analyzer that warns you if your method have a |
Beta Was this translation helpful? Give feedback.
-
I have a C# program with 'run' and 'stop' buttons. However, this task consists of several branches and dozens of methods. Previously, I had individually checked the state of ctsToken in each branch and method so that clicking 'stop' would immediately stop the task when it reached these branches. But today, I found that two inconspicuous methods did not check the state of ctsToken, meaning that clicking 'stop' would not immediately stop the task when it reached these methods, but would instead have to wait until they finished executing. I find it difficult to ensure that each method remembers to add the check for ctsToken's state, and when there are many methods, it is easy to overlook this.
At the same time, I haven't thought of how to detect such omissions in unit tests. Does anyone have a better way to handle it so that the task can be stopped immediately after clicking 'stop' no matter which method the program is executing in?
Beta Was this translation helpful? Give feedback.
All reactions