我在 ConcurrentDictionary 中有一个理解问题

问题描述

我有一个理解问题。在安全性和性能方面哪个更好?

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);
                }
            }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...