Skip to content

SynchronizationContext isn't properly restored on async call #1593

Closed

Description

@hlngo

The first OpenAsync() call results in Thread.CurrentThread switching from thread id 1 to another random thread. The subsequent calls to OpenAsync() do not cause this switch.

The consequence of the thread switch is that this may cause cross-thread operation. See code below.

private async void button1_Click(object sender, EventArgs e)
{
var strBuilder = new Npgsql.NpgsqlConnectionStringBuilder()
{
Host = "localhost",
Username = "postgres",
Password = "password"
};
using (var conn = new Npgsql.NpgsqlConnection(strBuilder.ConnectionString))
{
try
{
await conn.OpenAsync();
if (conn.State ==ConnectionState.Open)
{
MessageBox.Show("Connected");
this.button1.Text = "CROSS-THREAD";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Activity

  1. roji commented on Jun 6, 2017

    @roji
    Member

    The behavior you're describing is expected, and indeed all asynchronous operations function in this way. When you await an async method, you're accepting the fact that the lines of code following it (the continuation) may (but also might not) be executed in a different thread. In your specific example, the first time you open the connection, a physical connection is opened and so actual I/O occurs and a thread switch occurs. The second and thread time the connection pool probably returns the idle physical connection, meaning that no I/O actually occurs.

    In cases where thread switching may be an issue, e.g. UI frameworks where changes must be done by a single UI thread, the SynchronizationContext is there to make sure that continuations are scheduled for work on the proper thread. There are many posts out there describing how SynchronizationContext interacts with async/await in the context of Winforms/WPF to make sure that code is executed on the right thread.

    I'm going to close this as Npgsql is behaving as expected, but if you think otherwise (or need to understand this better) don't hesitate to post back here.

  2. hlngo commented on Jun 6, 2017

    @hlngo
    Author

    Roji, thanks for detailed explanation. I got this issue and went back to test with sqlserver client, mysql connector, sqlite and none of them has this issue. I read another issue #121 (#121) in this repos and you guys talking something about using true async. Not sure if it is related. My point here is this issue doesn't happen with other connectors while it always happens with npgsql.

  3. hlngo commented on Jun 7, 2017

    @hlngo
    Author

    Roji, I have read some more about what you explained. I found an interesting article on msdn: https://blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext-and-console-apps/
    It describes how await “brings you back to where you were.” I read similar things on other sites as well. I think it would be great if Npgsql can do that.

  4. roji commented on Jun 7, 2017

    @roji
    Member

    To make things clear, in normal sync I/O you thread blocks (sits around idly) while waiting for server responses. This is why you have the same thread before and after calling the synchronous Open(). The idea behind async is that the thread is released while waiting for the server response (which could take a long time), and that another thread picks up running the code after OpenAsync(). So, if you're doing await on any async operation and see the same thread ID (as seen via Thread.CurrentThread.ManagedThreadId), either that operation isn't actually implemented as async, or it had cached resources that allowed it to skip actual I/O for this specific invocation.

    If memory serves, last time I checked the standard MySQL ADO.NET provider indeed did not implement async (it also supported old versions of the .NET Framework, from before async/await was introduced). On the other hand, I'm 99% sure that SqlClient fully supports async, so you may want to go back and check things.

    Finally, the article you find explains the situation well: the point of SynchronizationContext is indeed to "bring you back to where you were", or in other words, to make sure the code after your await runs in the UI thread. However, this has nothing to do with Npgsql, it's a feature of the code calling Npgsql's OpenAsync(). Within Npgsql the SynchronizationContext is ignored as it should be (via an equivalent of ConfigureAwait(false), since code inside Npgsql does not rely on the UI thread. Your own function, awaiting on OpenAsync(), should have its SynchronizationContext properly set, and that is what will make your code resume back in the UI thread after Npgsql completes its own part.

    To better understand these concepts, you may want to play around with a simper async API, for example asynchronously opening a file or socket somewhere. You should see the same effects as with Npgsql.

  5. hlngo commented on Jun 7, 2017

    @hlngo
    Author

    Thanks Roji. I have got a bit clearer after reading your explanation and Stephen Cleary's article:
    https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

    However, I may need some diggings on why I don't see the same thing happening in other drivers. FYI, I was talking about the other MySQL: https://github.com/mysql-net/MySqlConnector

  6. roji commented on Jun 7, 2017

    @roji
    Member

    @hlngo yeah, Stephen Cleary has some other very useful articles on async/await, make sure you understand exactly what ConfigureAwait() does and how it interacts with SynchronizationContext.

    As to other providers, I really can't say... But you should see thread-switching everywhere where you await on a truly async operation which performs I/O, unless the SynchronizationContext is making your continuation run back on your UI thread (but then this should happen when using Npgsql as well).

    Good luck and let me know if you need more help (or find more info on other drivers).

  7. hlngo commented on Jun 7, 2017

    @hlngo
    Author

    @roji I think I got it why npgsql behaves like that. Npgsql sets the current synchronization context to null instead of use ConfigureAwait(false). See link:
    https://github.com/npgsql/npgsql/blob/2dd46e7c544caf3302ca7b89dd888a16dccf5c2c/src/Npgsql/PGUtil.cs
    When using ConfigureAwait(false), after leaving the OpenAsync(), the context will switch back to the previous context, Winforms context in this case.
    I also tried ReadAsync a big file as well as query big data in SQL Server, both of them always bring me back to the UI thread.
    Another quick search on other driver repos is that they don't touch the SynchronizationContext.
    Also, I have posted a question on StackOverflow to get more info from other people:
    https://stackoverflow.com/questions/44418761/cross-thread-exception-after-async-call
    Thanks again for your help and big thanks for your work on npgsql.

  8. hlngo commented on Jun 8, 2017

    @hlngo
    Author

    @roji Ok. I confirm that changing from ConfigureAwait(false) to NoSynchronizationContextScope causing the effect. I found the commit below on Sep 24 last year:
    366b4bf

    Then I went back to install 3.1.7, which is the release right before the commit above, and I don't see the cross-thread exception anymore. The thread id stays the same before and after calling OpenAsync(). I will post my findings to stackoverflow. It may help other people.

    What do you think about this?

  9. StephenCleary commented on Jun 8, 2017

    @StephenCleary

    I believe the NoSynchronizationContextScope (as it is currently used) is buggy. The scope must be disposed synchronously, before the method returns an incomplete task.

  10. added and removed on Jun 8, 2017
  11. added this to the 3.2.4 milestone on Jun 8, 2017
  12. roji commented on Jun 8, 2017

    @roji
    Member

    @StephenCleary, reading up on the stackoverflow thread I understand the issue. @hlngo, thanks for being insistent on this issue and diving into it. I'll switch to @StephenCleary's SynchronizationContextSwitcher for 3.2.4.

  13. reopened this on Jun 8, 2017
  14. hlngo commented on Jun 8, 2017

    @hlngo
    Author

    @roji @StephenCleary Thank you both for your work and explanation. I have learnt a lot from this discussion.

  15. changed the title [-]Thread switch after the very first OpenAsync() is called[/-] [+]SynchronizationContext isn't properly restored on async call[/+] on Jun 11, 2017
  16. added a commit that references this issue on Jun 11, 2017
    4b1f69f
  17. roji commented on Jun 12, 2017

    @roji
    Member

    Note: this has been fixed. You can test the new synchronization context switching mechanism (adapted from @StephenCleary's library) by using versions starting from 3.2.4-ci-00189 in the stable myget feed.

  18. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions