我正在尝试开发库存管理的应用程序,目前我正在尝试通过交易来添加/删除项目的概念证明。该站点将托管在 Windows Azure 上,因此我必须使用 SqlTransation 来执行事务(无 DTC)。
这是我的 POC 库代码:
public static void AddQuantityByProductId(int argProductId, int argQuantity)
{
UpdateQuantity(argProductId, argQuantity);
}
public static void ReduceQuantityByProductId(int argProductId, int argQuantity)
{
UpdateQuantity(argProductId, argQuantity * -1);
}
private static void UpdateQuantity(int argProductId, int argQuantity)
{
string conn = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
{
connection.Open();
using (SqlTransaction transaction =
connection.BeginTransaction(IsolationLevel.Serializable))
{
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandTimeout = 30;
command.CommandText = "select [Quantity] from StockItems where [Id] = '" + argProductId + "'";
int quantity = (int)command.ExecuteScalar();
int newQuantity = quantity + argQuantity;
command.CommandText = "UPDATE StockItems SET [Quantity] = " + newQuantity + " WHERE [Id] = '" + argProductId + "'";
command.ExecuteNonQuery();
transaction.Commit();
}
}
}
我用来测试系统的代码:
static void Main(string[] args)
{
int productId = 6; //hard coded Id , because the line already exists
for (int i = 0; i < 10; i++)
{
Parallel.For(0, 10, (j) =>
{
StockItemDal.AddQuantityByProductId(productId, 10);
StockItemDal.ReduceQuantityByProductId(productId, 10);
});
}
}
例外:
你能帮我找出问题吗?