upd:让我稍后重新表述我的问题。有N个双数。有 N 个专用线程,每个线程都更新自己的双数(_cachedProduct在下面的示例中)。
不知何故,我需要sum这些数字,并且我需要IndexUpdated在更改任何双数字后尽快引发事件(如果可以在 10 µs 或更短的时间内引发此类事件,那就太好了)。
以下是我尝试执行此任务的方式
================================================
为了计算证券交易所指数,我创建了private double[] _cachedProduct;字段。这些字段由许多线程编写
    // called from another threads
    public override void InstrumentUpdated(Instrument instrument)
    {
        if (!_initialized)
        {
            if (!Initialize())
            {
                return;
            }
        }
        int instrumentId = instrument.Id;
        OrderBook ob = Program.market.OrderBook(instrument);
        if (ob.MedianOrAskOrBid == null)
        {
            _cachedProduct[instrumentId] = 0;
        }
        else
        {
            _cachedProduct[instrumentId] = ((double) ob.MedianOrAskOrBid)*_ammounts[instrumentId];
        }
    }
_ammounts是预初始化的数组,请忽略Initialize方法和变量 - 它们可以正常工作。
在循环中,我只是对所有 _cachedProduct 求和,当值发生变化时,我会通知其他人。
        Task.Factory.StartNew(() =>
                {
                    while(true)
                    {
                        if (_initialized)
                        {
                            break;
                        }
                    }
                    while (true)
                    {
                        CalculateAndNotify();
                        //Thread.Sleep(5);
                    }
                }
            , TaskCreationOptions.LongRunning);
    protected void CalculateAndNotify()
    {
        var oldValue = Value;
        Calculate();
        if (oldValue != Value)
        {
            NotifyIndexChanged();
        } 
    }
    protected override void Calculate()
    {
        double result = 0;
        for (int i = 0; i < _instrumentIds.Count(); i++)
        {
            int instrumentId = _instrumentIds[i];
            if (_cachedProduct[instrumentId] == 0)
            {
                Value = null;
                return;
            }
            result += _cachedProduct[instrumentId];;
        }
        Value = result;
    }
我必须用它Interlocked来更新我的双精度_cachedProduct  值,但现在请忽略这个事实,您还看到此代码的其他问题吗?
我是否应该Calculate在内部调用方法,while(true)以便我always使用一个核心而不会延迟。我的机器有 24 个内核,所以我认为这没问题。
但是,如果没有Thread.Sleep(5)(评论),我确实看到整个程序的速度明显放缓,我不明白为什么。程序在许多地方执行慢了几十倍。
问题是我是否完全不使用while(true)任何锁定的想法是可以的。或者我应该引入一些锁定方法,以便仅Calculate在其中一个更新时进行索引_cachedProduct?