Vik*_*son 3 c# multithreading locking
我有一个单身类,看起来很像这样,
public class CfgHandler
{
private static readonly string ConfigDir = "Config";
public T Get<T>() where T : class, new()
{
string cfgFile = Path.Combine(ConfigDir, typeof(T).FullName + ".json");
if (File.Exists(cfgFile))
{
var reader = new JsonReader();
return reader.Read<T>(File.ReadAllText(cfgFile));
}
return null;
}
public void Set<T>(T instance) where T : class, new()
{
string cfgFile = Path.Combine(ConfigDir, typeof(T).FullName + ".json");
var writer = new JsonWriter();
string json = writer.Write(instance);
File.WriteAllText(cfgFile, json);
}
}
Run Code Online (Sandbox Code Playgroud)
该类用于多线程环境,我想添加锁.但是对于整个班级来说并不是一把锁,因为我不希望它们之间存在竞争条件cfg.Set<Foo>();,cfg.Set<Bar>()因为它们处理不同的数据.
我想过加入下面的类CfgHandler,
private static class Locks<T>
{
private static object _lock = new object();
public static object Lock { get { return _lock; } }
}
Run Code Online (Sandbox Code Playgroud)
然后像这样锁定(Get和Set),
public void Set<T>(T instance) where T : class, new()
{
lock(Locks<T>.Lock)
{
// save to disk
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了一些微不足道的事情吗?有没有更好的方法来实现我的目标?
每个实例锁定或锁定每种类型?
你使用它的方式(使用静态Locks<T>.Lock)意味着Set<Foo>即使在不同的CfgHandler实例上的每次调用都将共享相同的锁.那是你要的吗?我猜你只是锁定每个实例可能会更好 - 它会为你节省复杂性Locks<T>.只需声明一个私有实例成员(private object _lock = new object();)并使用它(lock(this._lock))
编辑如果您正在使用单个实例CfgHandler并希望锁定每种类型,那么我猜您的方法非常好.如果您没有使用单个实例,但仍希望锁定每个类型,那么只需确保使用实例Locks<T>而不是使其静态.