nhibernate-core
nhibernate-core copied to clipboard
BeginTransaction is not async results in connection to be opened async
BeginTransaction is not async results in connection to be opened async. I'm not entirely sure but I assume BeginTransaction will result in a transaction to be started if not already running thus a connection to be opened. I'm getting FirstChangeExceptions on my NpgSql setup
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10035): A non-blocking socket operation could not be completed immediately. 192.168.149.149:5433
In https://github.com/npgsql/npgsql/issues/1183 it is mentioned this is because the connection is opened via .Open instead of .OpenAsync. I looked in the code and DriverConnectionProvider supports async but it seems it isn't used. Further analys shows that DriverBase doesn't have an async BeginTransaction.
I think an async BeginTransaction makes sense but maybe there is a workaround?
but maybe there is a workaround
You can try to force session to open async connection before calling session.BeginTransaction. Something like:
await (session.GetSessionImplementation().ConnectionManager.GetConnectionAsync(cancelationToken)).ConfigureAwait(false);
@bahusoid thanks for that tip, I've created the following extension method around it which I'll test later.
static class SessionExt
{
public async static Task<ITransaction> BeginTransactionAsync(
this ISession session,
IsolationLevel isolationLevel = IsolationLevel.Unspecified,
CancellationToken cancellationToken = default
)
{
await session
.GetSessionImplementation()
.ConnectionManager
.GetConnectionAsync(cancellationToken)
.ConfigureAwait(false);
return session.BeginTransaction(isolationLevel);
}
}