Son*_*Ali 2 c# thread-safety static-classes
请考虑以下两种情况:
//Data Contract
public class MyValue
{
}
Run Code Online (Sandbox Code Playgroud)
场景1:使用静态助手类.
public class Broker
{
private string[] _userRoles;
public Broker(string[] userRoles)
{
this._userRoles = userRoles;
}
public MyValue[] GetValues()
{
return BrokerHelper.GetValues(this._userRoles);
}
}
static class BrokerHelper
{
static Dictionary<string, MyValue> _values = new Dictionary<string, MyValue>();
public static MyValue[] GetValues(string[] rolesAllowed)
{
return FilterForRoles(_values, rolesAllowed);
}
}
Run Code Online (Sandbox Code Playgroud)
场景2:使用实例类.
public class Broker
{
private BrokerService _service;
public Broker(params string[] userRoles)
{
this._service = new BrokerService(userRoles);
}
public MyValue[] GetValues()
{
return _service.GetValues();
}
}
class BrokerService
{
private Dictionary<string, MyValue> _values;
private string[] _userRoles;
public BrokerService(string[] userRoles)
{
this._userRoles = userRoles;
this._values = new Dictionary<string, MyValue>();
}
public MyValue[] GetValues()
{
return FilterForRoles(_values, _userRoles);
}
}
Run Code Online (Sandbox Code Playgroud)
如果在具有约100个不同角色和超过一千个用户的Web环境中使用,那么[Broker]场景中的哪一个将最佳扩展.
注意:随意采取任何替代方法.
您可以使用静态类或实例类来破坏线程.但是,正确获取线程的关键是确保两个线程不会同时尝试访问同一个资源.
对于静态类,根据定义,它只有一个副本,所有线程都需要很好地共享.
使用实例类,您可以为每个线程创建一个实例.如果确保每个线程只访问它自己的实例,并且实例属性和方法不依次访问其他共享资源,则它们应该是线程安全的.
在您的情况下,我没有看到初始化后类中的任何更改.如果你确保以线程安全的方式初始化静态类(这里似乎是这种情况),静态变量应该是线程安全的(因为对变量的只读访问)并且会更快一点,因为你没有创建和处理实例的开销.