BlockingCollection + UI Thread

I followed this tutorial to create a sequence of priorities and wrapped it in a blocking collection. I have a DataGrid that I hooked up to the main priority queue that emits change events. I can add items to the collection from the UI thread without freezing, and it blocks when the buffer is full, as intended.

Now, how can I use the elements? Here is what I have:

public DownloadViewModel()
{
    Queue = new ConcurrentPriorityQueue<DownloadItem>(10);
    Buffer = new BlockingCollection<KeyValuePair<int, DownloadItem>>(Queue, 10000);

    Task.Factory.StartNew(() =>
    {
        KeyValuePair<int, DownloadItem> item;
        while(!Buffer.IsCompleted)
        {
            if(Buffer.TryTake(out item))
            {
                // do something with the item
            }

            Thread.SpinWait(100000);
        }
    });
}

But as soon as I added that bit Task.Factory.StartNew, my application suddenly takes 30 seconds before a window appears (before it was instant), and when I add an item, I get an exception

This type of CollectionView does not support changes to the SourceCollection from a stream other than the Dispatcher stream.

, , ? BlockingCollection? 4 8 .

?

+3
2

CollectionChanged ...

public bool TryAdd(KeyValuePair<int, T> item)
{
    int pos = _queues.Take(item.Key + 1).Sum(q => q.Count);
    _queues[item.Key].Enqueue(item.Value);
    Interlocked.Increment(ref _count);
    Dispatcher.BeginInvoke(
        new Action(
            () =>
            NotifyCollectionChanged(
                new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, pos))
        ));
    return true;
}

ConcurrentPriorityQueue DispatcherObject. , .


NotifyCollectionChanged :

private void NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)
{
    lock (CollectionChanged)
    {
        if (CollectionChanged != null)
            Dispatcher.BeginInvoke(new Action(() => CollectionChanged(this, e)));
    }
}

BeginInvoke.

+2

[ , ]

" , ". , . !

+1

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


All Articles