2016-03-03 32 views
0

我開發一個Asp.net MVC項目的fatest請求對象的對象及方式的列表:訪問聲稱對

有一個列表存儲中的所有在線學生

有幾個方法: - 登錄(瞳孔p):如果登錄OK,對將被添加到學生列出 - 退出(瞳孔p):如果註銷OK,對將被刪除出瞳列表

- > 2種方法具有同樣的潛在問題是「修改時無法修改列表」,因爲有很多Pupil同時登錄系統和註銷。雖然添加一個學生其他正在從學生列表中刪除 - >異常拋出

我試圖使用鎖來鎖定列表,同時修改(插入/刪除),但這是一個好辦法嗎?你有更好的主意嗎?

最後一種方法是,根據權利要求(書B)

管理員把一些書在GUI中,所有的學生記錄可以看到這些書籍。他們可以索取他們想要的任何書。最快的學生聲稱將擁有該書。那麼我們如何才能知道最快速的請求者呢?更新數據行時。同時有很多書籍被許多學生聲稱。但是隻有一個最快的學生可以在聲明成功之後擁有某本書

您是否有解決方案?這個解決方案就像你發出命令購買股票一樣。最快的傢伙將擁有股票

請記住,有許多學生會同時做同樣的事情。因此,我們必須確保系統正常工作,準確

感謝你在前進, 最好的問候

+0

你剛剛使用的是名單?如果是這樣,那永遠不會被認爲是線程安全的。你嘗試過使用Concurrent包嗎? https://msdn.microsoft.com/en-us/library/dd381779(v=vs.110).aspx –

+0

@ Shane.C我會試試看 –

回答

0

我看到這裏的問題是,你的設計假定應用程序始終對,那名單關於誰有什麼書的絕對真相。服務器重置時會發生什麼?如果你的圖書館變得足夠大,需要第二臺服務器到應用程序呢?

您需要將您的列表保存在數據庫或某種其他類型的持久性介質中。在內存中保存列表將爲您提供讀/寫緩衝區,但列表必須從庫數據庫的持久層填充。

using System; 
using System.Collections.Concurrent; 


namespace TestArea 
{ 
    public class Pupil 
    { 
     public Guid Id { get; set; } 
     public string Name { get; set; } 

     public string UserName { get; set; }   
    } 

    public class Book 
    { 
     //Supports having more than one ISBN in the library... We may have more than one To Kill a Mockingbird in our school library 
     public Guid Id { get; set; } 
     public string ISBN { get; set; } 
    } 
    public class SchoolLibrary 
    { 
     private ConcurrentDictionary<Guid, Pupil> Pupils { get; set; } 
     private ConcurrentDictionary<Guid, Book> Books{ get; set; } 
     private ConcurrentDictionary<Guid, Guid> CheckOuts { get; set; } 

     public Pupil Login(string userName, string password) 
     { 
      //Call repository to authenticate pupil into library system 

      //Mocked return assuming password check success 
      var id = Guid.NewGuid(); 

      return Pupils.GetOrAdd(id, (i) => 
      { 
       //Replace with function to get student info 
       return new Pupil 
       { 
        Id = i, 
        Name = "Bac Clunky", 
        UserName = userName 
       }; 
      }); 
     } 

     public bool CheckOut(Guid pupilId, Guid bookId) 
     { 
      //If book exists 
      if (Books.ContainsKey(bookId)) 
      { 
       Guid currentOwner; 
       //...is not currently checked out by anyone 
       if (CheckOuts.TryAdd(bookId, pupilId)) 
       { 
        return true; //book is now checked out 
       } 

       if (CheckOuts.TryGetValue(bookId, out currentOwner)) 
       { 
        return currentOwner == pupilId; //returns true if pupil already has the book, false if another student has it 
       }      
      } 

      return false; //all other cases fail to check out book 
     } 
    } 
}