How to dispose TransactionScope in cancelable async/await?

前端 未结 5 1775

I\'m trying to use the new async/await feature to asynchronously work with a DB. As some of the requests can be lengthy, I want to be able to cancel them. The issue I\'m run

5条回答
  •  被撕碎了的回忆
    2020-12-24 00:58

    For targeting .NET Framework 4.6+, .NET Core 2.1+ or .NET Standard 2.0+

    Consider using Microsoft.Data.SqlClient, which brings together the System.Data.SqlClient components of .NET Framework and .NET Core under one roof. Also useful if you'd like to use some of the newer SQL Server features.

    Check out the repo or pull from nuget.

    Add using statement after adding the package:

    using Microsoft.Data.SqlClient;
    

    Example using C# 8:

    // transaction scope
    using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
    
    // connection
    await using var connection = new SqlConnection(_connectionString);
    
    // open connection asynchronously
    await connection.OpenAsync();
    await using var command = connection.CreateCommand();
    command.CommandText = "SELECT CategoryID, CategoryName FROM Categories;";
    
    // run command asynchronously
    await using var dataReader = await command.ExecuteReaderAsync();
    
    while (dataReader.Read())
    {
        Console.WriteLine("{0}\t{1}", dataReader.GetInt32(0), dataReader.GetString(1));
    }
    
    scope.Complete();
    

提交回复
热议问题