C # Secure use of LINQ for threads

I have a program that constantly reads and analyzes a large stream of data from WebSocket. All parsing takes place in a single thread within the client, and the data is organized into a tree SortedSet<T>for quick work.

All data is added, updated and deleted without fail.

The problem occurs when I try to access data from another thread. It will work fine, but somewhere along the line there is a race condition that will be hit in a minute or two.

Consider this code (running on its own thread) to update the interface in real time:

private async Task RenderOrderBook()
{
    var book = _client.OrderBook;

    while (true)
    {
        try
        {
            var asks = book.Asks.OrderBy(i => i.Price).Take(5).OrderByDescending(i => i.Price);
            var bids = book.Bids.OrderByDescending(i => i.Price).Take(5);

            orderBookView.BeginInvoke(new MethodInvoker(() =>
            {
                ...omitted due to irrelevance
            }));

            await Task.Delay(500);
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
    }
}

LINQ book. , i.Price (a decimal variable), , , i , null. , .

, , , LINQ OrderBy , node , , .

book.Asks book.Bids SortedSet<T> . node _asks.ToArray(), . , .

?

public PriceNode[] Asks
{
    get { return _asks.ToArray(); }
}

public PriceNode[] Bids
{
    get { return _bids.ToArray(); }
}
+4
1

, - . , , .

, - , . , : , . ? . , " " .

, . , , , , , . :

(, ) , , . , . , : . , , . ( -) , , Strobel № 1. "" . №2, , . -.

. , . , , . , , , , , , . , . № 2, -, , , - , . , , .

, , . , , . , , , , (-- ). , . , . , , , , . , №2, , , , . , , . , .

, , / . , Dictionary<,> . , , .

: / , . , , 100 , 100 , .

+4

Source: https://habr.com/ru/post/1685266/


All Articles