DataContext.BeginTransactionAsync(CancellationToken cancellationToken) Method
.NET Standard 2.x
Asynchronously starts a database transaction, using the isolation level specified by the ContextOptions
.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public virtual Task<IAdoDbTransaction> BeginTransactionAsync(CancellationToken cancellationToken)
Parameters
cancellationToken
CancellationToken
A cancellation token that can be used by other objects or threads to receive notice of cancellation.
Returns
Task<IAdoDbTransaction>
Returns a task that represents the asynchronous operation.
Examples
The following code example starts an asynchronous transaction using the isolation level specified by the ContextOptions
. It uses a CancellationTokenSource type parameter to make this operation cancelable.
using System;
using System.Data;
using System.Threading;
namespace Appeon.ApiDoc.DataContextExamples
{
public class BeginTransactionAsyncExample
{
private readonly SchoolContext _context;
public BeginTransactionAsyncExample(SchoolContext context)
{
_context = context;
}
public async void Example2(CancellationTokenSource cts)
{
try
{
// Starts the asynchronous transaction using the isolation level specified
// by the `ContextOptions`.
await _context.BeginTransactionAsync(cts.Token);
try
{
string sql = @"INSERT Department
(DepartmentId, Name,Budget,StartDate, Administrator)
VALUES (1, 'Engineering', 350000, '2007-09-01', 2)";
_context.SqlExecutor.Execute(sql);
// Attempts to commit the transaction.
_context.Commit();
Console.WriteLine("Record has been written to database.");
}
catch (Exception)
{
// Attempts to roll back the transaction asynchronously.
try
{
await _context.RollbackAsync();
}
catch (Exception ex2)
{
Console.WriteLine("Message: {0}", ex2.Message);
}
}
}
catch (OperationCanceledException e)
{
// The operation was cancelled before completion.
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
cts.Cancel();
}
}
}
}
Applies to
.NET Standard
2.x