MSDN含糊地提到:
只要未修改集合,ReadOnlyCollection <(Of <(T>)>)可以同时支持多个读取器.即便如此,通过集合枚举本质上不是一个线程安全的过程.为了在枚举期间保证线程安全,您可以在整个枚举期间锁定集合.要允许多个线程访问集合以进行读写,您必须实现自己的同步.
以下公共静态集合是否可以安全地让多个线程进行迭代?如果没有,.NET内置的内容是否安全?我是否应该删除ReadOnlyCollection并为SomeStrings属性getter的每次访问创建一个私有集合的新副本?我知道如果多个线程试图锁定公共集合可能会出现死锁问题,但这是一个内部库,我无法理解为什么我们会想要.
public static class WellKnownStrings {
public static readonly ICollection<string> SomeStrings;
static WellKnownStrings()
{
Collection<string> someStrings = new Collection<string>();
someStrings.Add("string1");
someStrings.Add("string2");
SomeStrings = new ReadOnlyCollection<string>(someStrings);
}
}
Run Code Online (Sandbox Code Playgroud)
her*_*ter 10
通常,永远不会更改其内部状态(一旦发布到外部调用者)的不可变对象可以被视为线程安全的.
一ReadOnlyCollection<T>但不是线程安全的本身,因为它是围绕现有的集合,其拥有者可以修改任何时候仅仅是包装.
OP中的示例虽然是线程安全的,但因为底层集合无法修改(至少在没有黑客攻击的情况下).
尽管您的解决方案很聪明,但我认为这可能会更好地满足您的需求,尤其是在代码重用方面。
public class WellKnownStrings : StringEnumeration
{
private WellKnownStrings(string specialString) :base(specialString)
{
}
public static IEnumerable<String> SpecialStrings
{
get
{
return GetAllStrings<WellKnownStrings>();
}
}
public static readonly WellKnownStrings String1 = new WellKnownStrings("SOME_STRING_1");
public static readonly WellKnownStrings String2 = new WellKnownStrings("SOME_STRING_2_SPECIAL");
public static readonly WellKnownStrings String3 = new WellKnownStrings("SOME_STRING_3_SPECIAL");
}
Run Code Online (Sandbox Code Playgroud)
这是我适应于描述的基础类。
public abstract class StringEnumeration : Enumeration
{
private static int _nextItemValue;
private static readonly object _initializeLock = new object();
protected StringEnumeration(string stringValue)
:base(0, stringValue)
{
if(stringValue == null)
{
throw new ArgumentNullException("stringValue");
}
lock(_initializeLock)
{
_nextItemValue++;
_value = _nextItemValue;
}
}
public static IEnumerable<string> GetAllStrings<T>()
where T: StringEnumeration
{
return GetAll<T>().Select(x => x.DisplayName);
}
private readonly int _value;
public override int Value
{
get
{
return _value;
}
}
public static explicit operator string(WellKnownStrings specialStrings)
{
return specialStrings.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
最初从Jimmy Bogard的博客中窃取并改编的代码 我所做的唯一更改是使Value属性在派生类中为虚拟,并使GetAll()不依赖于new T()通用参数,因为静态成员字段不需要实例即可获取反映价值。
public abstract class Enumeration : IComparable
{
private readonly int _value;
private readonly string _displayName;
protected Enumeration(int value, string displayName)
{
_value = value;
_displayName = displayName;
}
public virtual int Value
{
get { return _value; }
}
public string DisplayName
{
get { return _displayName; }
}
public override string ToString()
{
return DisplayName;
}
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
return typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Where(field => field.FieldType == typeof (T))
.Select(field => field.GetValue(null))
.Where(value =>value != null)
.Cast<T>();
}
public override bool Equals(object obj)
{
var otherValue = obj as Enumeration;
if (otherValue == null)
{
return false;
}
var typeMatches = GetType().Equals(obj.GetType());
var valueMatches = _value.Equals(otherValue.Value);
return typeMatches && valueMatches;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue)
{
var absoluteDifference = Math.Abs(firstValue.Value - secondValue.Value);
return absoluteDifference;
}
public static T FromValue<T>(int value) where T : Enumeration, new()
{
var matchingItem = parse<T, int>(value, "value", item => item.Value == value);
return matchingItem;
}
public static T FromDisplayName<T>(string displayName) where T : Enumeration, new()
{
var matchingItem = parse<T, string>(displayName, "display name", item => item.DisplayName == displayName);
return matchingItem;
}
private static T parse<T, K>(K value, string description, Func<T, bool> predicate) where T : Enumeration, new()
{
var matchingItem = GetAll<T>().FirstOrDefault(predicate);
if (matchingItem == null)
{
var message = string.Format("'{0}' is not a valid {1} in {2}", value, description, typeof(T));
throw new Exception(message);
}
return matchingItem;
}
public int CompareTo(object other)
{
return Value.CompareTo(((Enumeration)other).Value);
}
}
public static IEnumerable<T> GetAll<T>() where T : Enumeration, new()
{
var type = typeof(T);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly).Where(field=>);
foreach (var info in fields)
{
var instance = new T();
var locatedValue = info.GetValue(instance) as T;
if (locatedValue != null)
{
yield return locatedValue;
}
}
}
public override bool Equals(object obj)
{
var otherValue = obj as Enumeration;
if (otherValue == null)
{
return false;
}
var typeMatches = GetType().Equals(obj.GetType());
var valueMatches = _value.Equals(otherValue.Value);
return typeMatches && valueMatches;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue)
{
var absoluteDifference = Math.Abs(firstValue.Value - secondValue.Value);
return absoluteDifference;
}
public static T FromValue<T>(int value) where T : Enumeration, new()
{
var matchingItem = parse<T, int>(value, "value", item => item.Value == value);
return matchingItem;
}
public static T FromDisplayName<T>(string displayName) where T : Enumeration, new()
{
var matchingItem = parse<T, string>(displayName, "display name", item => item.DisplayName == displayName);
return matchingItem;
}
private static T parse<T, K>(K value, string description, Func<T, bool> predicate) where T : Enumeration, new()
{
var matchingItem = GetAll<T>().FirstOrDefault(predicate);
if (matchingItem == null)
{
var message = string.Format("'{0}' is not a valid {1} in {2}", value, description, typeof(T));
throw new Exception(message);
}
return matchingItem;
}
public int CompareTo(object other)
{
return Value.CompareTo(((Enumeration)other).Value);
}
}
Run Code Online (Sandbox Code Playgroud)
我提供的类安全,直观且可重用。ReadOnlyCollection<T>BUT(如herzmeister der welten)指出,您的用例也是线程安全的,但在许多情况下并非如此。它实际上也没有公开可写的ICollection成员,因为对这些成员的任何调用都会引发异常。
如果有人有兴趣知道我最终在这里做了什么,在看到乔恩·斯基特(当然)的回答后,我会这样说:
public static class WellKnownStrings
{
public const string String1= "SOME_STRING_1";
public const string String2= "SOME_STRING_2_SPECIAL";
public const string String3= "SOME_STRING_3_SPECIAL";
public static IEnumerable<string> SpecialStrings
{
get
{
yield return String2;
yield return String3;
}
}
}
Run Code Online (Sandbox Code Playgroud)
它没有为调用者提供其余的ICollection<T>功能,但在我的情况下不需要。
| 归档时间: |
|
| 查看次数: |
1287 次 |
| 最近记录: |