我需要保护操作免受方法范围中的局部变量



假设我有以下方法,该方法在完成某些工作后被称为回调。

public class MyClass
    {
        private static object _synblock = new object();
    public void MyCallBackMethod()
    {
        Dictionary<int, int> myDict = new Dictionary<int, int>();
        lock(_synblock)
        {
            myDict.Add(1, 1);
        }
    }
}

此方法可以通过多个线程调用。在这种情况下,我是否需要同步在此方法范围中定义的本地变量 myDict 执行的任何操作(就像我在上面执行的那样)?还是完全不必要?

这是完全不必要的。每次调用MyCallbackMethod时,都会实例化一个新的myDict对象。如果多个线程同时使用

,则只需要保护对Dictionary<,>的访问

一般规则不是要保护实例级成员(和数据)免受多线程环境中的并发访问。理由非常简单:多线程是一个单独的问题。

我的建议是制作一个多线程包装器,该包装器只知道如何同步访问。反过来,这需要具有一个可以暴露您的班级功能的基类或界面。

public interface ISomeInterface
{
    void MyCallBackMethod();
}
public class MyClass : ISomeInterface
{
    private int Data { get; set; }
    public void MyCallBackMethod()
    {
        Dictionary<int, int> myDict = new Dictionary<int, int>();
        myDict.Add(1, 1);
        // access this.Data - this is the part that would
        // make problems in case of multithreaded access
    }
}
public class ThreadSafe : ISomeInterface
{
    private ISomeInterface Contained { get; }
    private object SyncRoot { get; } = new object();
    public ThreadSafe(ISomeInterface contained)
    {
        this.Contained = contained;
    }
    public void MyCallBackMethod()
    {
        lock (this.SyncRoot)
        {
            this.Contained.MyCallBackMethod();
        }
    }
}

它完全不必要,因为线程之间未共享本地变量。所以永远不要有纠纷

最新更新