新聞中心
在向大家詳細(xì)介紹Linq開放式并發(fā)之前,首先讓大家了解下Linq開放式并發(fā)控制,然后全面介紹Linq開放式并發(fā)。

Linq開放式并發(fā)控制
在 LINQ to SQL 對象模型中,當(dāng)以下兩個(gè)條件都得到滿足時(shí),就會(huì)發(fā)生“Linq開放式并發(fā)沖突”:客戶端嘗試向數(shù)據(jù)庫提交更改;數(shù)據(jù)庫中的一個(gè)或多個(gè)更新檢查值自客戶端上次讀取它們以來已得到更新。 此沖突的解決過程包括查明對象的哪些成員發(fā)生沖突,然后決定您希望如何進(jìn)行處理。
Linq開放式并發(fā)(Optimistic Concurrency)
說明:這個(gè)例子中在你讀取數(shù)據(jù)之前,另外一個(gè)用戶已經(jīng)修改并提交更新了這個(gè)數(shù)據(jù),所以不會(huì)出現(xiàn)沖突。
- //我們打開一個(gè)新的連接來模擬另外一個(gè)用戶
- NorthwindDataContext otherUser_db = new NorthwindDataContext();
- var otherUser_product =
- otherUser_db.Products.First(p => p.ProductID == 1);
- otherUser_product.UnitPrice = 999.99M;
- otherUser_db.SubmitChanges();
- //我們當(dāng)前連接
- var product = db.Products.First(p => p.ProductID == 1);
- product.UnitPrice = 777.77M;
- try
- {
- db.SubmitChanges();//當(dāng)前連接執(zhí)行成功
- }
- catch (ChangeConflictException)
- {
- }
說明:我們讀取數(shù)據(jù)之后,另外一個(gè)用戶獲取并提交更新了這個(gè)數(shù)據(jù),這時(shí),我們更新這個(gè)數(shù)據(jù)時(shí),引起了一個(gè)并發(fā)沖突。系統(tǒng)發(fā)生回滾,允許你可以從數(shù)據(jù)庫檢索新更新的數(shù)據(jù),并決定如何繼續(xù)進(jìn)行您自己的更新。
- //當(dāng)前用戶
- var product = db.Products.First(p => p.ProductID == 1);
- //我們打開一個(gè)新的連接來模擬另外一個(gè)用戶
- NorthwindDataContext otherUser_db = new NorthwindDataContext() ;
- var otherUser_product =
- otherUser_db.Products.First(p => p.ProductID == 1);
- otherUser_product.UnitPrice = 999.99M;
- otherUser_db.SubmitChanges();
- //當(dāng)前用戶修改
- product.UnitPrice = 777.77M;
- try
- {
- db.SubmitChanges();
- }
- catch (ChangeConflictException)
- {
- //發(fā)生異常!
- }
網(wǎng)站欄目:Linq開放式并發(fā)深入剖析
網(wǎng)頁地址:http://fisionsoft.com.cn/article/djjedie.html


咨詢
建站咨詢
