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

SynchronizationContext improperly restored #31

Open
OwnageIsMagic opened this issue Sep 25, 2023 · 3 comments
Open

SynchronizationContext improperly restored #31

OwnageIsMagic opened this issue Sep 25, 2023 · 3 comments

Comments

@OwnageIsMagic
Copy link

OwnageIsMagic commented Sep 25, 2023

var syncCtx = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(syncCtx == null ? _detectBlockingSyncCtx : new DetectBlockingSynchronizationContext(_monitor, syncCtx));
try
{
await _next(httpContext);
}
finally
{
SynchronizationContext.SetSynchronizationContext(syncCtx);
}

SetSynchronizationContext after awaiting on task restores context on continuation thread (not caller).
See
npgsql/npgsql#1593
https://stackoverflow.com/questions/44418761/cross-thread-exception-after-async-call/44424562#44424562
@benaadams project seems like not maintained, just for your (and others) information.

@maxisam
Copy link

maxisam commented Oct 18, 2024

I don't know if this is true. I think it is a bit different from the SO link you post.

In that SO post, it clear the SynchronizationContext of the original thread, so after await, it could run on a different thread.

It is like using ConfigureAwait(false), which was exactly what npgsql try to achieve

But here we actually give it a context and create one if there is no context.

so after await, it should go back to the original thread.

@OwnageIsMagic
Copy link
Author

@maxisam SynchronizationContext is thread local
And DetectBlockingSynchronizationContext doesn't guarantee await will return to the same thread (it even doesn't override Post/Send methods)

@OwnageIsMagic OwnageIsMagic changed the title SynchronizationContext imprperly restored SynchronizationContext improperly restored Oct 20, 2024
@maxisam
Copy link

maxisam commented Oct 21, 2024

@OwnageIsMagic I guess I am confused about how await work. I thought await always return to the original context and that is tied with the thread. That is why we don't use configureAwait(false) for UI related code, because it will use any available thread from the thread pool. But if we only use await, it will return to the original thread if there is a context involved.

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

No branches or pull requests

2 participants