コード例 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="connection"></param>
        /// <param name="executeAsync"></param>
        /// <param name="transaction"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private static async Task <TResult> TransactionalExecuteAsync <TResult>(this NpgsqlConnection connection,
                                                                                Func <Task <TResult> > executeAsync,
                                                                                NpgsqlTransaction transaction,
                                                                                CancellationToken cancellationToken = default)
        {
            // Variables
            var result         = default(TResult);
            var hasTransaction = transaction != null;

            // Open
            await connection.EnsureOpenAsync(cancellationToken);

            // Ensure transaction
            if (hasTransaction == false)
            {
#if NET5_0
                transaction = await connection.BeginTransactionAsync(cancellationToken);
#else
                transaction = connection.BeginTransaction();
#endif
            }

            try
            {
                // Execute
                if (executeAsync != null)
                {
                    result = await executeAsync();
                }

                // Commit
                if (hasTransaction == false)
                {
                    await transaction.CommitAsync(cancellationToken);
                }
            }
            catch
            {
                // Rollback
                if (hasTransaction == false)
                {
                    await transaction.RollbackAsync(cancellationToken);
                }

                // Throw
                throw;
            }
            finally
            {
                // Dispose
                if (hasTransaction == false)
                {
                    await transaction.DisposeAsync();
                }
            }

            // Return
            return(result);
        }
コード例 #2
0
        public async Task CommitAsync(CancellationToken token)
        {
            if (_options.OwnsTransactionLifecycle)
            {
                await Transaction.CommitAsync(token).ConfigureAwait(false);

                await Transaction.DisposeAsync().ConfigureAwait(false);
            }
        }