本文介绍了通过的SqlTransaction在.net中禁用读/写表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用的SqlTransaction在.NET 2.0,这样,当我开始从表中读取数据,该表将阻止他人(其他程序)读取/写入到该表?

How to use SqlTransaction in .net 2.0 so that when I start reading data from a table, that table is blocked for others (other programs) to read/write to that table?

如果的SqlTransaction是不是一个好的选择,比的是什么?

If SqlTransaction is not a good option, than what is?

推荐答案

这应该通过使用串行化的事务与 TABLOCKX 提示在最初的SELECT语句中允许的。 TABLOCKX 应在表上采取的排它锁,以便其他人可以使用该表和串行化的事务应该要求 HOLDLOCK 这意味着,所有的锁一直保持到事务结束(你可以用 HOLDLOCK 直接)。

This should be allowed by using Serializable transaction together with TABLOCKX hint in initial select statement. TABLOCKX should take exclusive lock on the table so nobody else can use that table and Serializable transaction should demand HOLDLOCK which means that all locks are kept until end of the transaction (you can use HOLDLOCK directly).

更新:我只是测试不同的场景在Management Studio中,它  看起来你并不需要  明确使用序列化  交易。在任何使用TABLOCKX  交易就足够了。

要知道,这样的做法可能是很大的瓶颈,因为只有一个事务可以对这些表进行操作=没有并发。即使你阅读和处理单条记录由百万人的工作其他人将无法使用该表工作,直到您的交易结束。

Be aware that such approach can be big bottleneck because only one transaction can operate on such table = no concurrency. Even if you read and work with single record from million nobody else will be able to work with the table until your transaction ends.

所以,命令应该是这样的:

So the command should look like:

SELECT * FROM Table WITH (TABLOCKX) WHERE ...

要使用串行化的事务,你可以使用的SqlTransaction

To use serializable transaction you can use SqlTransaction:

using (SqlConnection connection = new SqlConnection(connectionString))
{
  connection.Open();
  SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.Serializable);

  try
  {
    ...
    transaction.Commit();
  }
  catch (Exception)
  {
    transaction.Rollback();
    ...
  }
}

System.Transactions.TransactionScope (默认隔离级别应该是序列化)。

Or System.Transactions.TransactionScope (default isolation level should be Serializable).

using (TransactionScope scope = new TransactionScope())
{
  using (SqlConnection connection = new SqlConnection(connectionString))
  {
    ...
  }
  scope.Complete();
}

这篇关于通过的SqlTransaction在.net中禁用读/写表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:51