Ben.BlockingDetector icon indicating copy to clipboard operation
Ben.BlockingDetector copied to clipboard

SynchronizationContext improperly restored

Open OwnageIsMagic opened this issue 2 years ago • 3 comments

https://github.com/benaadams/Ben.BlockingDetector/blob/fce6c534dfcee6ba8cb3ef74d246211b81f5cbeb/src/Ben.BlockingDetector/BlockingDetectionMiddleware.cs#L31-L42 SetSynchronizationContext after awaiting on task restores context on continuation thread (not caller). See https://github.com/npgsql/npgsql/issues/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.

OwnageIsMagic avatar Sep 25 '23 01:09 OwnageIsMagic

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.

maxisam avatar Oct 18 '24 14:10 maxisam

@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 avatar Oct 20 '24 13:10 OwnageIsMagic

@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.

maxisam avatar Oct 21 '24 16:10 maxisam