C#如何确保用户提供线程安全的对象来运行
我有一个服务器类,它在接受TcpClient时引发一个事件,其主要任务是获取一个用户定义的对象,并将其传递到属于TcpClient的线程中。e、 gC#如何确保用户提供线程安全的对象来运行,c#,.net-3.5,thread-safety,C#,.net 3.5,Thread Safety,我有一个服务器类,它在接受TcpClient时引发一个事件,其主要任务是获取一个用户定义的对象,并将其传递到属于TcpClient的线程中。e、 g public class MyData : UserData {} public GetUserDataEventArg : CancelEventArg { UserData Data { get; set; } } public class Server { public event EventHandler<GetUserDataEve
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; }
公共类MyData:UserData{}
public GetUserDataEventArg:CancelEventArg{UserData数据{get;set;}}
公共类服务器{public event EventHandler GetUserData=null;}
//在预期用途中,每个线程都有自己的数据。
public void GetUserDataEventHandler1(对象发送方,GetUserDataEventArg e){e.Data=new MyData();}
//危险使用,共享成员数据可能未实现线程安全。
public void GetUserDataEventHandler2(对象发送方,GetUserDataEventArg e){e.Data=m_myData;}
如何确保使用是线程安全的?欢迎实现相同目标的其他实现。提前感谢。您无法编写代码来获取可以检查该对象以确定其是否是线程安全的对象 因此,您必须在以下两者之间进行选择:
无论哪种方式,您都需要记录这一点,以便编写调用代码的人知道需要什么,以及他在其中扮演的角色。您无法编写代码来获取可以检查该对象以确定其是否是线程安全的对象 因此,您必须在以下两者之间进行选择:
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上下文中使用此功能,则此功能将不起作用,因为请求可以利用所谓的“线程敏捷性”,这意味着请求可能在其生命周期中传递给其他线程。尝试以下方法:
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上下文中使用它,这将不起作用,因为请求可以利用所谓的“线程敏捷性”,这意味着请求可能在其生命周期中传递给不同的线程