Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to poll from worker thread for cancellation
    primarykey
    data
    text
    <p>I have a UI which spawns off a background worker thread which performs a complex tree of tasks and sub-tasks that takes about a minute to complete. </p> <p>A requirement is that the background worker task must be capable of being cancelled once it has begun.</p> <p>At the moment my solution is naive and makes the code a mess. When a cancel button is pressed in the UI, a cancel token is set. The worker thread periodically (between tasks) polls this token and if it is set, it exits:</p> <pre><code>void ThreadWorkerHandler(CancelToken cancelToken) { DoTask1(cancelToken); if (cancelToken.IsSet) return; DoTask2(cancelToken); if (cancelToken.IsSet) return; DoTask3(cancelToken); if (cancelToken.IsSet) return; DoTask4(cancelToken); } void DoTask2(CancelToken cancelToken) { DoSubTask2a(); if (cancelToken.IsSet) return; DoSubTask2b(); if (cancelToken.IsSet) return; DoSubTask2c(); if (cancelToken.IsSet) return; } </code></pre> <p>Is there a better solution? I was toying for something like a SoLongAs statement that would automatically pepper the checks in and automatically and raise an internal exception if the condition was met, which would be internally caught at the end of the loop, eg:</p> <pre><code>void ThreadWorkerHandler(CancelToken cancelToken) { SoLongAs (canelToken.IsSet == false) { DoTask1(cancelToken); DoTask2(cancelToken); DoTask3(cancelToken); DoTask4(cancelToken); } } </code></pre> <p>But I imagine that wouldn't work for some reason, also more importantly I doubt something like this actually exists. If not is there a better way to handle this scenario than I am currently using? Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload