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