2
我有這段代碼,在兩個單獨的線程中並行運行。它可以正常工作幾次,但在某個隨機點拋出InvalidOperationException:InvalidOperationException在執行事務時執行SqlCommand
事務要麼不與當前連接關聯,要麼已經完成。
在例外情況下,我正在使用visual studio查看事務內部並驗證其連接是否正常設置。也是command.Transaction._internalTransaction。 _transactionState設置爲活動,IsZombied屬性設置爲false。
這是一個測試應用程序,我使用Thread.Sleep創建更長的事務並導致重疊。
爲什麼可能拋出異常,我該怎麼辦?
IDbCommand command = new SqlCommand("Select * From INFO");
IDbConnection connection = new SqlConnection(connectionString);
command.Connection = connection;
IDbTransaction transaction = null;
try
{
connection.Open();
transaction = connection.BeginTransaction();
command.Transaction = transaction;
command.ExecuteNonQuery(); // Sometimes throws exception
Thread.Sleep(forawhile); // For overlapping transactions running in parallel
transaction.Commit();
}
catch (ApplicationException exception)
{
if (transaction != null)
{
transaction.Rollback();
}
}
finally
{
connection.Close();
}