You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
WaitAsync(CancellationToken) does not terminate when cancellation occurs #1265
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
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.
@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.
@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).
@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.
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.
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.
Activity
roji commentedon Sep 6, 2016
Unfortunately this is a .NET limitation -
NetworkStream.ReadAsync()itself doesn't respect the cancellation token, and so the same is true withWaitAsync().It should still be possible to close a connection while waiting though - I'll look into this.
rwasef1830 commentedon Sep 6, 2016
@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.
roji commentedon Sep 6, 2016
@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).
rwasef1830 commentedon Sep 6, 2016
@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 XXby 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.
roji commentedon Sep 12, 2016
@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 callNpgsqlCommand.Cancel()to trigger PostgreSQL cancellation - it's just that cancellation tokens don't trigger it.For
WaitAsyncspecifically (as opposed to commands) it may make sense for cancellation tokens to trigger PostgreSQL cancellation, as there's noNpgsqlCommandobject on which to callCancel(), 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
NpgsqlCommandbut not forWaitAsync. 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.
maxkornev commentedon May 11, 2017
Hi!
Are there any estimates ?
roji commentedon May 22, 2017
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, aSELECT 1will be sent to the server, and then the thread performing theWaitAsync()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.