简体   繁体   中英

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. eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM