ExecuteNonQueryAsync and commit in a SQL Transaction

折月煮酒 提交于 2020-12-29 12:00:23

问题


I am after some help with a piece of code I have created, I am attempting to make an Async SQL call from c# within a transaction, for example I might be updating or deleting rows from a table.

This is what I have so far, but I cannot seem to find much information on doing this in a transaction, from what I have here and what I understand so far, I believe it may attempt to commit the transaction before the command has fully completed if the command is time-consuming. If you could advise / point me to an example I would really appreciate it.

var sqlQuery = "delete from table";
        using (var connection = new SqlConnection(ConnectionString))
        {
            await connection.OpenAsync();
            using (var tran = connection.BeginTransaction())
            {
                using (var command = new SqlCommand(sqlQuery, connection, tran))
                {
                    await command.ExecuteNonQueryAsync();
                    tran.Commit();
                }
            }
        }

Thanks,


回答1:


Your code looks good. I just added a try/catch on the execution of the command so you can roll back your transaction if it fails. Because you are using the await keyword on the line await command.ExecuteNonQueryAsync(); execution will block until the method returns regardless of how long it takes (unless you get a timeout exception from the command itself in which case you should set the command's execution timeout higher or figure out why its taking so long).

    var sqlQuery = "delete from table";
    using (var connection = new SqlConnection(ConnectionString))
    {
        await connection.OpenAsync();
        using (var tran = connection.BeginTransaction())
        using (var command = new SqlCommand(sqlQuery, connection, tran))
        {
            try {
                await command.ExecuteNonQueryAsync();
            } catch {
                tran.Rollback();
                throw;
            }
            tran.Commit();
        }
    }


来源:https://stackoverflow.com/questions/36040111/executenonqueryasync-and-commit-in-a-sql-transaction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!