我需要使用锁(createPaletteLocker)吗?我正在使用它,因为我认为这样做可以避免在其他线程正在读取它时写入 ColorPaletteHandle.palettesList[type]。
编辑 1:字典仅在静态构造函数中设置。因此,我将不再更改(添加/删除),但它所持有的立场将从 null 更改为相应创建的调色板。
public static class ColorPaletteHandle
{
private static readonly object createPaletteLocker = new object();
private static Dictionary<ColorPaletteType, ColorPalette> palettesList = null;
static ColorPaletteHandle()
{
palettesList = new Dictionary<ColorPaletteType, ColorPalette>();
palettesList.Add(ColorPaletteType.Default, ColorPaletteHandle.defaultPalette);
palettesList.Add(ColorPaletteType.EdgesHighlight, ColorPaletteHandle.edgesHighlight);
palettesList.Add(ColorPaletteType.GrayScale, ColorPaletteHandle.grayScale);
palettesList.Add(ColorPaletteType.HeatMap, ColorPaletteHandle.heatMap);
}
/// <summary>
/// Gets a palette.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static ColorPalette GetPalette(ColorPaletteType type)
{
ColorPalette pal = null;
lock (ColorPaletteHandle.createPaletteLocker)
{
pal = ColorPaletteHandle.palettesList[type];
if (pal == null)
{
ColorPaletteHandle.palettesList[type] = ColorPaletteHandle.CreatePalette(type);
pal = ColorPaletteHandle.palettesList[type];
}
}
return pal;
}
//stuff...
}