2011-07-23 35 views
1

我有一個服務器類,在接受TcpClient後,引發一個事件,其主要任務是讓用戶定義的對象傳遞到屬於TcpClient的線程中。例如C#如何確保用戶提供線程安全對象的功能

public class MyData : UserData {} 
public GetUserDataEventArg : CancelEventArg { UserData Data { get; set; } } 
public class Server { public event EventHandler<GetUserDataEventArg> GetUserData = null; } 
// intended usage, each thread has its own data. 
public void GetUserDataEventHandler1(object sender, GetUserDataEventArg e) { e.Data = new MyData(); } 
// dangerous usage, shared member data may not have thread safety implemented. 
public void GetUserDataEventHandler2(object sender, GetUserDataEventArg e) { e.Data = m_myData; } 

如何確保使用是線程安全的?其他實現相同目標的實現也受到歡迎。提前致謝。

回答

3

你無法編寫代碼,它需要一個可以檢查該對象的對象來確定它是否是線程安全的。

因此,你必須選擇之間:

  1. 假設它線程安全的,把負擔該對象的提供者,即得。呼叫者
  2. 假設它不是線程安全的,把負擔你,來處理對象的線程安全的方式

無論哪種方式,你需要記錄本,這樣的人寫的調用代碼知道期望什麼,以及他的角色是什麼。

2

試試這個:

public class MyData 
{ 
    private int _originatingThreadId; 

    public MyData() 
    { 
     _originatingThreadId = Thread.CurrentThread.ManagedThreadId; 
    } 

    public void ThreadUnsafeMethod() 
    { 
     if(Thread.CurrentThread.ManagedThreadId != _originatingThreadId) 
      throw new Exception("This method should only be called from the thread on which the original object was created"); 
    } 
} 

請記住,這是不行的,如果你使用這個從一個ASP.Net背景下,作爲請求可以利用一種叫做「線程靈活性」,這意味着請求可能會在其生命週期中傳遞給其他線程。

相關問題