Skip to content

WaitAsync(CancellationToken) does not terminate when cancellation occurs #1265

Closed

Description

@lsedlacek

With Npgsql 3.1.7.0 on .NET 4.5.1, and the following console app body:

var conn = new NpgsqlConnection(MyConnectionString);

conn.Open();
using (var cmd = new NpgsqlCommand(@"LISTEN ""foo"";", conn))
{
    cmd.ExecuteNonQuery();
}

var debug = CancellationToken.None;

var waiting = Observable.Create<Unit>(
    async (o, ctoken) =>
    {
        debug = ctoken;

        while (!ctoken.IsCancellationRequested)
        {
            await conn.WaitAsync(ctoken);
        }

        return Disposable.Empty;
    })
    .Subscribe();

var notifying = Observable
    .FromEventPattern<NotificationEventHandler, NpgsqlNotificationEventArgs>(
        eh => conn.Notification += eh,
        eh => conn.Notification -= eh
    ).Select(x => x.EventArgs)
    .Subscribe(x => Console.WriteLine($"{x.PID} {x.Condition} {x.AdditionalInformation}"));

Console.ReadKey();

notifying.Dispose();
waiting.Dispose();

Console.WriteLine($"debug.IsCancellationRequested = {debug.IsCancellationRequested}");

conn.Dispose();

Running SELECT pg_notify('foo', 'payload'); in pgAdmin, and then pressing a key in the console app produces the following output:

12893 foo payload
debug.IsCancellationRequested = True

Unhandled Exception: System.InvalidOperationException: Reset() called on connector with state Waiting
   at Npgsql.NpgsqlConnector.Reset()
   at Npgsql.ConnectorPool.Release(NpgsqlConnector connector)
   at Npgsql.NpgsqlConnection.ReallyClose(Boolean wasBroken)
   at Npgsql.NpgsqlConnection.Close()
   at Npgsql.NpgsqlConnection.Dispose(Boolean disposing)
   at System.ComponentModel.Component.Dispose()
   at foo2.Program.Main() in C:\dev\tmp\wait_async_ctoken\Program.cs:line 54

Activity

  1. roji commented on Sep 6, 2016

    @roji
    Member

    Unfortunately this is a .NET limitation - NetworkStream.ReadAsync() itself doesn't respect the cancellation token, and so the same is true with WaitAsync().

    It should still be possible to close a connection while waiting though - I'll look into this.

  2. added this to the 3.1.8 milestone on Sep 6, 2016
  3. rwasef1830 commented on Sep 6, 2016

    @rwasef1830
    Contributor

    @roji It is actually consulted only right before the operation begins, but once started there is no way to stop it except by disposing the stream. Best way is register a cancellation callback on the passed token that disposes the stream then deregisters itself.

  4. roji commented on Sep 6, 2016

    @roji
    Member

    @rwasef1830, yep, that's what I meant. Async I/O in .NET is unfortunately unfriendly to cancellation and timeout.

    However, disposing the stream means breaking the connection, a violent affair which I don't think should occur just because a user has signaled a cancellation. A user should be able to close (or dispose) the NpgsqlConnection themselves, which would terminate the wait. Users who wish this behavior for cancellation can register a callback on their cancellation token themselves (but I don't really think it should be the default behavior).

  5. rwasef1830 commented on Sep 6, 2016

    @rwasef1830
    Contributor

    @roji There's another way used by MySQL (maybe SQL Server), and that is Disposing on a reader would spawn a new connection that issues KILL XX by the "process id" of the thread handling the reader. Thus terminating the operation but not the connection.

    The disadvantage would be the problem of the pool, but this can be alleviated by having a dedicated "cancel" connection always available (and lazily creating it on first cancel).

    There's a Cancel API on the base DbConnection contract as well. But not sure if the user should handle themselves or make it default behavior.

  6. modified the milestones: 3.2, 3.1.8 on Sep 12, 2016
  7. roji commented on Sep 12, 2016

    @roji
    Member

    @rwasef1830 that's an interesting idea.

    PostgreSQL indeed has cancellation support, and this is already exposed in PostgreSQL when calling DbCommand.Cancel(). This indeed terminates the operation but not the connection. It's a somewhat heavy operation - it means establishing a new TCP socket to PostgreSQL, although it's not a full-blown connection with a dedicated process at the server side. This also means it's impossible to pool "cancellation-only" connections.

    At some point I looked at having async cancellation tokens trigger PostgreSQL cancellation for NpgsqlCommand - take a look at #633. I ended up deciding against this, because at some point NetworkStream will probably support cancellation tokens (see https://github.com/dotnet/corefx/issues/5211), and it seems more correct to keep cancellation tokens for that. In other words, for now triggering cancellation tokens (mostly) does nothing because they're not supported in NetworkStream, but when that support gets added it will (probably) just start working. Users are of course free to call NpgsqlCommand.Cancel() to trigger PostgreSQL cancellation - it's just that cancellation tokens don't trigger it.

    For WaitAsync specifically (as opposed to commands) it may make sense for cancellation tokens to trigger PostgreSQL cancellation, as there's no NpgsqlCommand object on which to call Cancel(), so there's no other API to trigger PostgreSQL cancellation.

    However, note that PostgreSQL cancellation has one serious drawback over NetworkStream cancellation (if/when support for that gets added) - it depends on being able to contact the server to perform the operation. In various dropped connection scenario, PostgreSQL cancellation will simply do nothing, whereas a NetworkStream cancellation will always succeed. This is why it's ideal to have both as an option, which is the case for NpgsqlCommand but not for WaitAsync. Another option would be to first try PostgreSQL cancellation, and if that doesn't work after a certain amount of time, trigger NetworkStream cancellation.

    Moving this to 3.2 and keeping open for more discussion/thinking.

  8. removed this from the 3.2 milestone on Sep 25, 2016
  9. maxkornev commented on May 11, 2017

    @maxkornev

    Hi!
    Are there any estimates ?

  10. roji commented on May 22, 2017

    @roji
    Member

    Hmm, I seem to have fixed this for 3.2 - cancellation tokens do work well with WaitAsync, see test NotificationTests.WaitAsyncCancellation.

    It's true that NetworkStream's ReadAsync() does not honor cancellation tokens (https://github.com/dotnet/corefx/issues/14308). However, it so happens that Npgsql's WaitAsync() also has optional keepalive support - if no notification occurs within a given time, a SELECT 1 will be sent to the server, and then the thread performing the WaitAsync() will receive the response. Cancellation is implemented in the same way - a keepalive is sent, its response is read and in addition we check whether the cancellation token has been triggered.

    If you encounter any issues with this mechanism please open a new issue.

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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions