Possible Duplicate:
Are C# auto-implemented static properties thread-safe?
在下面的示例类中
static class Shared
{
public static string[] Values { get; set; }
}
许多读取器线程定期读取 Values
字符串数组,而有时单个写入器会使用 setter 将整个数组替换为新值。我需要使用 ReaderWriterLock
还是 C# 会自动处理?
编辑:在我的例子中,唯一需要的“线程安全”是:当读者正在搜索一个值时,当作者替换数组时,不会发生任何不好的事情。我不在乎读者是否会立即使用新值,只要他们将来会使用它就可以了
这种使用是线程安全的:
string[] localValues = Shared.Values;
for (int index = 0; index < localValues.length; index++)
ProcessValues(localValues[index]);
这种使用不是线程安全的,会导致越界异常:
for (int index = 0; index < Shared.Values.Length; index++)
ProcessValues(Shared.Values[index]);
我更愿意通过做这样的事情来使线程安全调用更自然:
static class Shared
{
private static string[] values;
public static string[] GetValues() { return values; }
public static void SetValues(string[] values) { Shared.values = values; }
}
当然,用户仍然可以将 GetValues() 放在循环中,它会同样糟糕,但至少它显然是糟糕的。
根据情况,更好的解决方案可能是分发副本,这样调用代码就根本无法改变数组。这是我通常会做的,但它可能不适合您的情况。
static class Shared
{
private static string[] values;
public static string[] GetValues()
{
string[] currentValues = values;
if (currentValues != null)
return (string[])currentValues.Clone();
else
return null;
}
public static void SetValues(string[] values)
{
Shared.values = values;
}
}