gpt4 book ai didi

c# - 如何在处理 SqlTransaction 之前检查状态

转载 作者:太空狗 更新时间:2023-10-30 00:05:19 25 4
gpt4 key购买 nike

我有以下使用 SqlTransaction 的代码。我已经在 catch 和 finally block 中调用了 dispose。但是我没有在调用 Dispose() 之前检查它是否已经被处理。我们如何在调用 Dispose() 之前检查 SqlTransaction 是否已经被释放?

我提到了MSDN:SqlTransaction.Dispose Method .但这不包括我的问题。

还提到了 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction.dispose(v=vs.100).aspx

注意:我已经知道 TransactionScopeSqlTransaction 有优势。但我想了解 SqlTransaction 的处置。

代码

 using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();

SqlTransaction transaction = null;

try
{
transaction = connection.BeginTransaction();

sessionID = GetSessionIDForAssociate(connection, empID, transaction);
//Other code

//Commit
transaction.Commit();
}
catch
{
//Rollback
if (transaction != null)
{
transaction.Rollback();
transaction.Dispose();
}

//Throw exception
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
}

最佳答案

How can we check whether the SqlTransaction is already disposed before calling Dispose()?

你不必。调用 dispose 两次不会给你带来任何问题。

Dispose - MSDN

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

但是如果您只想调用 Dispose 一次,那么您可以使用 bool 标志来设置事务处理的时间,也可以将其设置为 null。或者在 catch block 中删除对 dispose 的调用,因为 finally block 将始终被调用。

由于 SqlTransaction 实现了 IDisposable , 如果将它与 using block 一起使用会更好。像这样的东西:

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();

using (SqlTransaction transaction = connection.BeginTransaction())
{
try
{
sessionID = GetSessionIDForAssociate(connection, empID, transaction);
//Other code

//Commit
transaction.Commit();
}
catch
{
//Rollback
if (transaction != null)
{
transaction.Rollback();
}

//Throw exception
throw;
}
}
}

由于using block 的行为类似于try/finally block,它会确保在交易完成时对其进行处理(即使发生异常)。因此您不必手动调用 Dispose

关于c# - 如何在处理 SqlTransaction 之前检查状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14438736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com