Skip to content
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

Merged
merged 5 commits into from
Nov 11, 2020
Merged

Simplify cancellation #32

merged 5 commits into from
Nov 11, 2020

Conversation

alanmcgovern
Copy link
Owner

This allows us to do cancellation synchronously (in a threadsafe way), and so we can remove a fair chunk of complexity from this codepath.

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.
Comment on lines +117 to +118
CurrentSearchCancellation?.Cancel ();
var currentSearch = CurrentSearchCancellation = CancellationTokenSource.CreateLinkedTokenSource (token);
Copy link
Contributor

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.

Copy link
Owner Author

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 :)

alanmcgovern and others added 2 commits November 11, 2020 22:39
Co-authored-by: Marius Ungureanu <therzok@gmail.com>
This isn't an async method so don't suffix it
with the word 'Async'.
@alanmcgovern alanmcgovern merged commit 310d63d into master Nov 11, 2020
@alanmcgovern alanmcgovern deleted the simplify-cancellation branch November 11, 2020 22:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants