문제

Say I create a task

bool aBoolean = true;

Task.Factory.StartNew(() =>
    while(aBooloean)    {
       ...
    }
}

Is it better to exit the task by having a global boolean to exit the Task?

Or ist it better to use CancellationTokenSource?

When is it appropriate to use a CancellationTokenSource to end a Task?

Does it just throw an exception when you use CancellationTokenSource and leave things in a inconsistent state?

Thanks

도움이 되었습니까?

해결책

Having a "global" boolean runs the risk of being optimized or cached into CPU cache and you may not see a change in value. CancellationTokenSource is the recommended method for cancelling a Task. The Task uses the Token to test if cancellation is requested and simply returns from the Task's Action delegate. No need to throw an exception if you don't want to.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top