-
Notifications
You must be signed in to change notification settings - Fork 156
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Simplify cancellation #32
Conversation
As the library was recently refactored to allow the listeners to be re-instantiated when someone calls NatUtility.StopDiscovery and then NatUtility.StartDiscovery, it is now easier to handle cleanup. Rather than relying on await async tasks in potentially blocking ways, we can simply dispose the underlying sockets. This will interrupt any pending send/receive calls safely. As a result, we can remove some of the complexity surrounding cancellation.
This is an internal method and we never pass in CancellationToken.None. As a result this is dead code.
CurrentSearchCancellation?.Cancel (); | ||
var currentSearch = CurrentSearchCancellation = CancellationTokenSource.CreateLinkedTokenSource (token); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is definitely not thread-safe though.If it's called from different threads, this can race in certain conditions. Prefer using Interlocked.CompareExchange
here and then you got a sure-fire way to cancel and dispose the current token source.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That kind of thread safety isn't a concern in this specific place!
These classes are internal so there's no direct access to them. The way to access them is to call methods on the static class, NatUtility
, and these methods are wrapped in a lock.
As such, we're guaranteed this part of the code will always be singlethreaded. That said, thread safety is a concern elsewhere :)
Co-authored-by: Marius Ungureanu <therzok@gmail.com>
This isn't an async method so don't suffix it with the word 'Async'.
This allows us to do cancellation synchronously (in a threadsafe way), and so we can remove a fair chunk of complexity from this codepath.