Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cheenamalhotra/0ae1d2114e32a38731568213156fbabf to your computer and use it in GitHub Desktop.
Save cheenamalhotra/0ae1d2114e32a38731568213156fbabf to your computer and use it in GitHub Desktop.
Reproduce Transaction Aborted Exception from System.Data.SqlClient
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Transactions;
namespace TestMultithreadedTS
{
class Program
{
private const string _connectionString = "Server=localhost; Integrated Security=true;";
/* Execute below SQL to prepare table:
* CREATE TABLE Messages(Id BIGINT IDENTITY(1, 1) PRIMARY KEY, MessageText NVARCHAR(1024));
**/
static async Task Main()
{
// Increment to 100000 and execute in debug mode to reproduce issue with Microsoft.Data.SqlClient.
// Issue reproducible with System.Data.SqlClient with below count.
var count = 10000;
var tasks = new Task[count];
for (var i = 0; i < count; i++)
{
int x = i;
tasks[x] = Task.Run(() => LogMessageAsync(x));
}
await Task.WhenAll(tasks);
Console.WriteLine("Completed test run");
}
private static async Task LogMessageAsync(int i)
{
try
{
using (var ts = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
using (var coon = new SqlConnection(_connectionString))
{
await coon.OpenAsync();
using (var cmd = coon.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Messages(MessageText) VALUES (@MessageText)";
cmd.Parameters.Add(
new SqlParameter("@MessageText", DbType.String)
{
Value = $"Message no {i}"
});
cmd.ExecuteNonQuery();
}
}
ts.Complete();
Console.WriteLine(i + "Completed");
}
}
catch (Exception e)
{
Console.WriteLine(i + " " + e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment