2014-04-18 33 views
3

我爲多線程的異步套接字編寫了一個緩衝區類。我希望確保在其他操作完成之前不允許對緩衝區進行任何操作(讀取,寫入)。這個怎麼做?代碼是這樣的:如何鎖定緩衝區引用

public class ByteBuffer { 
    private static ManualResetEvent mutex = 
     new ManualResetEvent(false); 
    byte[] buff; 
    int capacity; 
    int size; 
    int startIdx; 

    public byte[] Buffer { 
     get { return buff; } 
    } 
    public int StartIndex { 
     get { return startIdx; } 
    } 
    public int Capacity { 
     get { return capacity; } 
    } 

    public int Length { 
     get { return size; } 
    } 

    // Ctor 
    public ByteBuffer() { 
     capacity = 1024; 
     buff = new byte[capacity]; 
     size = startIdx = 0; 
    } 
    // Read data from buff without deleting 
    public byte[] Peek(int s){ 
     // read s bytes data 
    } 
    // Read data and delete it 
    public byte[] Read(int s) { 
     // read s bytes data & delete it 
    } 

    public void Append(byte[] data) { 
     // Add data to buff 
    } 

    private void Resize() { 
     // resize the buff 
    } 


} 

如何鎖定吸氣劑?

+0

可能重複http://stackoverflow.com/questions/505515/c-sharp-thread-safety-with -get-set) – Tarec

回答

3

我建議使用lock例如

public class A 
{ 
    private static object lockObj = new object(); 

    public MyCustomClass sharedObject; 
    public void Foo() 
    { 
    lock(lockObj) 
    { 

     //codes here are safe 
     //shareObject..... 
    } 
    } 

} 
[具有get/set C#線程安全(的
+0

如果在鎖內「返回」會好嗎?我要試試這個。 – zoujyjs

+0

@zoujyjs是的,這是好的 – RezaRahmati

+0

而順便說一句,如果我有一個可以通過多線程訪問的'private int state'成員,'private volatile int state'就足夠了這種情況嗎? – zoujyjs