我觉得这种行为不应该发生。以下是场景:
启动一个长时间运行的SQL事务。
运行SQL命令的线程被终止(不是由我们的代码终止的!)
当线程返回托管代码时,SqlConnection的状态为“已关闭”-但是事务仍在SQL服务器上打开。
SQLConnection可以重新打开,并且可以尝试在事务上调用回滚,但它没有效果(我不会期望这种行为。重点是没有办法访问数据库上的事务并将其回滚。)
问题仅在于当线程中止时未正确清理事务。这是.Net 1.1、2.0和2.0 SP1的问题。我们正在运行.Net 3.5 SP1。
以下是说明此问题的示例程序。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Threading;
namespace ConsoleApplication1
{
class Run
{
static Thread transactionThread;
public class ConnectionHolder : IDisposable
{
public void Dispose()
{
}
public void executeLongTransaction()
{
Console.WriteLine("Starting a long running transaction.");
using (SqlConnection _con = new SqlConnection("Data Source=<YourServer>;Initial Catalog=<YourDB>;Integrated Security=True;Persist Security Info=False;Max Pool Size=200;MultipleActiveResultSets=True;Connect Timeout=30;Application Name=ConsoleApplication1.vshost"))
{
try
{
SqlTransaction trans = null;
trans = _con.BeginTransaction();
SqlCommand cmd = new SqlCommand("update <YourTable> set Name = 'XXX' where ID = @0; waitfor delay '00:00:05'", _con, trans);
cmd.Parameters.Add(new SqlParameter("0", 340));
cmd.ExecuteNonQuery();
cmd.Transaction.Commit();
Console.WriteLine("Finished the long running transaction.");
}
catch (ThreadAbortException tae)
{
Console.WriteLine("Thread - caught ThreadAbortException in executeLongTransaction - resetting.");
Console.WriteLine("Exception message: {0}", tae.Message);
}
}
}
}
static void killTransactionThread()
{
Thread.Sleep(2 * 1000);
// We're not doing this anywhere in our real code. This is for simulation
// purposes only!
transactionThread.Abort();
Console.WriteLine("Killing the transaction thread...");
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
using (var connectionHolder = new ConnectionHolder())
{
transactionThread = new Thread(connectionHolder.executeLongTransaction);
transactionThread.Start();
new Thread(killTransactionThread).Start();
transactionThread.Join();
Console.WriteLine("The transaction thread has died. Please run 'select * from sysprocesses where open_tran > 0' now while this window remains open. \n\n");
Console.Read();
}
}
}
}
有一个Microsoft Hotfix针对.NET2.0 SP1,旨在解决这个问题,但是我们显然拥有更新的DLL(.Net 3.5 SP1),它们的版本号与此热修复程序中列出的版本号不匹配。
有人能解释一下这个行为吗?为什么ThreadAbort仍然不能正确清理SQL事务? .NET 3.5 SP1是否不包含此热修补程序,或者这是技术上正确的行为?
waitfor
。 - user166390