问题描述
private ConcurrentDictionary<string,ProfitTarget> chartTraderTP;
if (chartTraderTP.ContainsKey(orderId))
{
//Store values for later use in Mouse Events
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
//We can draw the Rectangle based on the TextLayout used above
if (!chartTraderTP[orderId].IsMovingOrder
&& (ChartTraderdisplayStyle == ChartTraderdisplayStyle.Own
|| ChartTraderdisplayStyle == ChartTraderdisplayStyle.Both))
{
rendertarget.FillRectangle(rectTextOrderLabelTP,tpAreaBrushDx);
rendertarget.DrawRectangle(rectTextOrderLabelTP,tpOutlineBrushDx,LabelOutlinewidthTP);
rendertarget.DrawTextLayout(vectText,tpTextLayout,tpTextBrushDx,SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
}
或
private ConcurrentDictionary<string,ProfitTarget> chartTraderTP;
//Store values for later use in Mouse Events
if (chartTraderTP.ContainsKey(orderId))
{
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
}
//We can draw the Rectangle based on the TextLayout used above
if (chartTraderTP.ContainsKey(orderId) && !chartTraderTP[orderId].IsMovingOrder
&& (ChartTraderdisplayStyle == ChartTraderdisplayStyle.Own
|| ChartTraderdisplayStyle == ChartTraderdisplayStyle.Both))
{
rendertarget.FillRectangle(rectTextOrderLabelTP,tpAreaBrushDx);
rendertarget.DrawRectangle(rectTextOrderLabelTP,LabelOutlinewidthTP);
rendertarget.DrawTextLayout(vectText,SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
代码执行频率很高,我希望访问尽可能快,但仍然是线程安全的。
解决方法
两者都不安全,因为您正在执行多个操作,同时假设集合在操作之间没有变化,这不是一个安全的假设。
由于您想要使用许多不同的操作并且需要整个部分在逻辑上是原子的,因此只需使用常规的 Dictionary
并锁定对它的访问。
lock (chartTraderTP)
{
//Store values for later use in Mouse Events
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
//We can draw the Rectangle based on the TextLayout used above
if (!chartTraderTP[orderId].IsMovingOrder && (ChartTraderDisplayStyle == ChartTraderDisplayStyle.Own || ChartTraderDisplayStyle == ChartTraderDisplayStyle.Both))
{
RenderTarget.FillRectangle(rectTextOrderLabelTP,tpAreaBrushDx);
RenderTarget.DrawRectangle(rectTextOrderLabelTP,tpOutlineBrushDx,LabelOutlineWidthTP);
RenderTarget.DrawTextLayout(vectText,tpTextLayout,tpTextBrushDx,SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
}