如何异步加载可观察的集合列表?

时间:2012-03-06 14:54:57

标签: c# image asynchronous observablecollection

我正在我的应用中加载图片。显示需要一些时间。

我将项目收集为可观察的收集列表,其中图像存储在独立存储中。

我想以异步方式获取和显示图像?

1 个答案:

答案 0 :(得分:2)

试试

public class ObservableCollectionThreadSafe<T> : ObservableCollection<T>
{
    // Override the event so this class can access it
    public override event NotifyCollectionChangedEventHandler CollectionChanged;

    public ObservableCollectionThreadSafe()
    {
    }

    public ObservableCollectionThreadSafe(IEnumerable<T> items)
        : base(items)
    {
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        // Be nice - use BlockReentrancy like MSDN said
        using (BlockReentrancy())
        {
            NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;
            if (eventHandler == null)
                return;

            Delegate[] delegates = eventHandler.GetInvocationList();

            // Walk thru invocation list
            foreach (NotifyCollectionChangedEventHandler handler in delegates)
            {
                DispatcherObject dispatcherObject = handler.Target as DispatcherObject;

                // If the subscriber is a DispatcherObject and different thread
                if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
                {
                    // Invoke handler in the target dispatcher's thread
                    dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);
                }
                else // Execute handler as is
                    handler(this, e);
            }
        }
    }
}
编辑:顺便说一下,这不是我的代码,它是由某人在网上发现的...所以“有人”,如果你认识到自己,那么你应该为此感到荣幸......