Reputation: 303
i have a method that needs to react to an isCanceling flag. It should be able to be changed elsewhere and noticed within the method, but I don't want to be able to change the boolean from within the method. What I have below, I think will be able to read a bool if the passed in boolean is changed elsewhere, but I want to ensure that isCanceling cannot be changed within this context. Is that possible?
public static bool DoSomething(ref bool isCanceling)
{
while(whileLoopFlag && !isCanceling)
{
//doTheThing()
}
}
Upvotes: 3
Views: 69
Reputation: 203821
Use a CancellationTokenSource
/CancellationToken
to allow code external to this method to cancel it. In addition to having an API where an object can notify another of cancellation, it will properly synchronize the underlying boolean such that the objects can be used from multiple threads without any problems.
Upvotes: 7