开发者

C# How to ensure user provides thread safe object to function

I have a Server class that upon accepted a TcpClient, raises an event whose primary job is to get a user defined object to be passed into the thread belonging to the TcpClient. e.g.

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; } 

How can I ensure the usage is thread-safe? Other implementations that achieves the same objective are welcomed. Thanks in advance.


There is no way you can write code that takes an object that can inspect that object to figure out if it is thread-safe.

As such, you have to chose between:

  1. Assume it is thread-safe, put the burden on the provider of that object, ie. the caller
  2. Assume it is not thread-safe, put the burden on you, to handle that object in a thread-safe manner

Either way you need to document this so that the person writing the calling code knows what to expect, and what his role is in it.


Try this:

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");
    }
}

Keep in mind that this won't work if you're using this from an ASP.Net context, as requests can utilise something called "thread agility", which means the request might be passed to a different thread during its lifecycle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜