ahm*_*md0 5 .net c# database asp.net concurrency
说明我的问题最简单的方法是使用这个C#代码:
using (SqlCommand cmd = new SqlCommand("SELECT * FROM [tbl]", connectionString))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
//Somewhere at this point a concurrent thread,
//or another process changes the [tbl] table data
//Begin reading
while (rdr.Read())
{
//Process the data
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么rdr在这种情况下数据会发生什么?
我实际上测试了这个。测试代码:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("select * from test", conn))
{
using (var reader = comm.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
if ((string)reader[1] == "stop")
{
throw new Exception("Stop was found");
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了进行测试,我使用一些虚拟数据初始化了表(确保不包含值为“stop”的行)。然后我就上线了一个断点int i = 0;。当执行在断点处停止时,我在表中插入了一行带有“停止”值的行。
结果是,根据表中初始行的数量,抛出Exception/不抛出。我没有尝试确定行限制的确切位置。对于十行,Exception没有抛出 ,这意味着读者没有注意到从另一个进程添加的行。一万行时,抛出异常。
所以答案是:这取决于。如果不将命令/读取器包装在 a 中Transaction,您就不能依赖这两种行为。
强制性免责声明:这就是它在我的环境中的工作原理......
编辑:
我在我的开发机器上使用本地 Sql 服务器进行了测试。它将自身报告为:
微软 SQL Server 2008 R2 (SP1) - 10.50.2550.0 (X64)
关于交易:
这是我使用事务的代码:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
conn.Open();
using (var trans = conn.BeginTransaction())
using (SqlCommand comm = new SqlCommand("select * from test", conn, trans))
{
using (var reader = comm.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
i++;
if ((string)reader[1] == "stop")
{
throw new Exception("Stop was found");
}
}
}
trans.Commit();
}
}
Run Code Online (Sandbox Code Playgroud)
在此代码中,我创建事务时没有显式指定隔离级别。这通常意味着System.Data.IsolationLevel.ReadCommitted将使用它(我认为可以在 Sql Server 设置中的某处设置默认隔离级别)。在这种情况下,读者的行为与以前相同。如果我将其更改为使用:
...
using (var trans = conn.BeginTransaction(System.Data.IsolationLevel.Serializable))
...
Run Code Online (Sandbox Code Playgroud)
“停止”记录的插入被阻止,直到事务被提交为止。这意味着当读取器处于活动状态时,Sql Server 不允许对底层数据进行任何更改。
| 归档时间: |
|
| 查看次数: |
1172 次 |
| 最近记录: |