并發可能產生的三種問題
臟讀
定義:A事務執行過程中B事務讀取了A事務的修改,但是A事務并沒有結束(提交),A事務后來可能成功也可能失敗。
比喻:A修改了源代碼并且并沒有提交到源代碼系統,A直接通過QQ將代碼發給了B,A后來取消了修改。
代碼示例
代碼如下:
[TestMethod]
public void 臟讀_測試()
{
//前置條件
using (var context = new TestEntities())
{
Assert.AreEqual(1, context.Tables.Count());
}
var autoResetEvent = new AutoResetEvent(false);
var transactionOptions1 = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
var transactionOptions2 = new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted };
using (var ts1 = new TransactionScope(TransactionScopeOption.Required, transactionOptions1))
{
//添加數據
using (var context = new TestEntities())
{
context.Tables.Add(new Table() { Id = Guid.NewGuid(), Name = "段光偉" });
context.SaveChanges();
}
ThreadPool.QueueUserWorkItem(data =>
{
using (var ts2 = new TransactionScope(TransactionScopeOption.Required, transactionOptions2))
{
新聞熱點
疑難解答
圖片精選