Is WPF binding to concurrent collections safe?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I was wondering, if it is safe to bind a WPF control to a concurrent collection, specifically a wrapper class around one of the System.Collections.Concurrent collections that also implements INotifyCollectionChanged?



I understand that CollectionChanged must be invoked on the UI-thread (and without the index parameters). But, what happens, if another thread manipulates the source collection while the UI is updating itself? Does WPF just gracefully ignore the problem (like it does in so many other places)?










share|improve this question


















  • 1





    To be absolutely sure, the collection's enumerator must be threadsafe, which is the case in ConcurentBag. Fortunatelly, wpf comes with BindingOperations.EnableCollectionSynchronization, that solves this problem even with ObservableCollection or List. Immutable collections are also an option

    – Liero
    Nov 25 '18 at 9:02




















0















I was wondering, if it is safe to bind a WPF control to a concurrent collection, specifically a wrapper class around one of the System.Collections.Concurrent collections that also implements INotifyCollectionChanged?



I understand that CollectionChanged must be invoked on the UI-thread (and without the index parameters). But, what happens, if another thread manipulates the source collection while the UI is updating itself? Does WPF just gracefully ignore the problem (like it does in so many other places)?










share|improve this question


















  • 1





    To be absolutely sure, the collection's enumerator must be threadsafe, which is the case in ConcurentBag. Fortunatelly, wpf comes with BindingOperations.EnableCollectionSynchronization, that solves this problem even with ObservableCollection or List. Immutable collections are also an option

    – Liero
    Nov 25 '18 at 9:02
















0












0








0








I was wondering, if it is safe to bind a WPF control to a concurrent collection, specifically a wrapper class around one of the System.Collections.Concurrent collections that also implements INotifyCollectionChanged?



I understand that CollectionChanged must be invoked on the UI-thread (and without the index parameters). But, what happens, if another thread manipulates the source collection while the UI is updating itself? Does WPF just gracefully ignore the problem (like it does in so many other places)?










share|improve this question














I was wondering, if it is safe to bind a WPF control to a concurrent collection, specifically a wrapper class around one of the System.Collections.Concurrent collections that also implements INotifyCollectionChanged?



I understand that CollectionChanged must be invoked on the UI-thread (and without the index parameters). But, what happens, if another thread manipulates the source collection while the UI is updating itself? Does WPF just gracefully ignore the problem (like it does in so many other places)?







wpf multithreading data-binding concurrent-collections






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 23:48









mikemike

459317




459317








  • 1





    To be absolutely sure, the collection's enumerator must be threadsafe, which is the case in ConcurentBag. Fortunatelly, wpf comes with BindingOperations.EnableCollectionSynchronization, that solves this problem even with ObservableCollection or List. Immutable collections are also an option

    – Liero
    Nov 25 '18 at 9:02
















  • 1





    To be absolutely sure, the collection's enumerator must be threadsafe, which is the case in ConcurentBag. Fortunatelly, wpf comes with BindingOperations.EnableCollectionSynchronization, that solves this problem even with ObservableCollection or List. Immutable collections are also an option

    – Liero
    Nov 25 '18 at 9:02










1




1





To be absolutely sure, the collection's enumerator must be threadsafe, which is the case in ConcurentBag. Fortunatelly, wpf comes with BindingOperations.EnableCollectionSynchronization, that solves this problem even with ObservableCollection or List. Immutable collections are also an option

– Liero
Nov 25 '18 at 9:02







To be absolutely sure, the collection's enumerator must be threadsafe, which is the case in ConcurentBag. Fortunatelly, wpf comes with BindingOperations.EnableCollectionSynchronization, that solves this problem even with ObservableCollection or List. Immutable collections are also an option

– Liero
Nov 25 '18 at 9:02














1 Answer
1






active

oldest

votes


















1














That depends on the implementation of your wrapper. Let's make a simple example adding INotifyCollectionChanged to a BlockingCollection<T> allowing calls of non UI threads:



public void AddNotified(T item)
{
base.Add(item);

var args = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add,
item,
Count - 1);

//Ensure no items are changed until the UI is updated

Application.Current.Dispatcher.Invoke(() =>
CollectionChanged?.Invoke(this, args));
}


The implementation of Add itself is threadsafe, but to be sure the UI shows the current items the implementation you need to ensure that there are no other items are changed between adding and updating (See comment in code).



WPF updates the UI based on the NotifyCollectionChangedAction and updated items passed at raising the INotifyCollectionChanged.CollectionChanged. This means the UI relys on this information. The result: An interim collection update leads to an unsynchronized UI until the update was raised or a NotifyCollectionChangedAction.Reset was called and the UI shows different items like inside your source collection.



Synchronizing collections with the UI is a very wide and intresting topic. There are already multiple solutions available that may match your specific problem. To give you some possible approaches to solve problems like this have a look at here are some links:




  • Is there a Threadsafe Observable collection in .NET 4?

  • Threadsafe ObservableCollection

  • BindingOperations.EnableCollectionSynchronization






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463419%2fis-wpf-binding-to-concurrent-collections-safe%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    That depends on the implementation of your wrapper. Let's make a simple example adding INotifyCollectionChanged to a BlockingCollection<T> allowing calls of non UI threads:



    public void AddNotified(T item)
    {
    base.Add(item);

    var args = new NotifyCollectionChangedEventArgs(
    NotifyCollectionChangedAction.Add,
    item,
    Count - 1);

    //Ensure no items are changed until the UI is updated

    Application.Current.Dispatcher.Invoke(() =>
    CollectionChanged?.Invoke(this, args));
    }


    The implementation of Add itself is threadsafe, but to be sure the UI shows the current items the implementation you need to ensure that there are no other items are changed between adding and updating (See comment in code).



    WPF updates the UI based on the NotifyCollectionChangedAction and updated items passed at raising the INotifyCollectionChanged.CollectionChanged. This means the UI relys on this information. The result: An interim collection update leads to an unsynchronized UI until the update was raised or a NotifyCollectionChangedAction.Reset was called and the UI shows different items like inside your source collection.



    Synchronizing collections with the UI is a very wide and intresting topic. There are already multiple solutions available that may match your specific problem. To give you some possible approaches to solve problems like this have a look at here are some links:




    • Is there a Threadsafe Observable collection in .NET 4?

    • Threadsafe ObservableCollection

    • BindingOperations.EnableCollectionSynchronization






    share|improve this answer




























      1














      That depends on the implementation of your wrapper. Let's make a simple example adding INotifyCollectionChanged to a BlockingCollection<T> allowing calls of non UI threads:



      public void AddNotified(T item)
      {
      base.Add(item);

      var args = new NotifyCollectionChangedEventArgs(
      NotifyCollectionChangedAction.Add,
      item,
      Count - 1);

      //Ensure no items are changed until the UI is updated

      Application.Current.Dispatcher.Invoke(() =>
      CollectionChanged?.Invoke(this, args));
      }


      The implementation of Add itself is threadsafe, but to be sure the UI shows the current items the implementation you need to ensure that there are no other items are changed between adding and updating (See comment in code).



      WPF updates the UI based on the NotifyCollectionChangedAction and updated items passed at raising the INotifyCollectionChanged.CollectionChanged. This means the UI relys on this information. The result: An interim collection update leads to an unsynchronized UI until the update was raised or a NotifyCollectionChangedAction.Reset was called and the UI shows different items like inside your source collection.



      Synchronizing collections with the UI is a very wide and intresting topic. There are already multiple solutions available that may match your specific problem. To give you some possible approaches to solve problems like this have a look at here are some links:




      • Is there a Threadsafe Observable collection in .NET 4?

      • Threadsafe ObservableCollection

      • BindingOperations.EnableCollectionSynchronization






      share|improve this answer


























        1












        1








        1







        That depends on the implementation of your wrapper. Let's make a simple example adding INotifyCollectionChanged to a BlockingCollection<T> allowing calls of non UI threads:



        public void AddNotified(T item)
        {
        base.Add(item);

        var args = new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Add,
        item,
        Count - 1);

        //Ensure no items are changed until the UI is updated

        Application.Current.Dispatcher.Invoke(() =>
        CollectionChanged?.Invoke(this, args));
        }


        The implementation of Add itself is threadsafe, but to be sure the UI shows the current items the implementation you need to ensure that there are no other items are changed between adding and updating (See comment in code).



        WPF updates the UI based on the NotifyCollectionChangedAction and updated items passed at raising the INotifyCollectionChanged.CollectionChanged. This means the UI relys on this information. The result: An interim collection update leads to an unsynchronized UI until the update was raised or a NotifyCollectionChangedAction.Reset was called and the UI shows different items like inside your source collection.



        Synchronizing collections with the UI is a very wide and intresting topic. There are already multiple solutions available that may match your specific problem. To give you some possible approaches to solve problems like this have a look at here are some links:




        • Is there a Threadsafe Observable collection in .NET 4?

        • Threadsafe ObservableCollection

        • BindingOperations.EnableCollectionSynchronization






        share|improve this answer













        That depends on the implementation of your wrapper. Let's make a simple example adding INotifyCollectionChanged to a BlockingCollection<T> allowing calls of non UI threads:



        public void AddNotified(T item)
        {
        base.Add(item);

        var args = new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Add,
        item,
        Count - 1);

        //Ensure no items are changed until the UI is updated

        Application.Current.Dispatcher.Invoke(() =>
        CollectionChanged?.Invoke(this, args));
        }


        The implementation of Add itself is threadsafe, but to be sure the UI shows the current items the implementation you need to ensure that there are no other items are changed between adding and updating (See comment in code).



        WPF updates the UI based on the NotifyCollectionChangedAction and updated items passed at raising the INotifyCollectionChanged.CollectionChanged. This means the UI relys on this information. The result: An interim collection update leads to an unsynchronized UI until the update was raised or a NotifyCollectionChangedAction.Reset was called and the UI shows different items like inside your source collection.



        Synchronizing collections with the UI is a very wide and intresting topic. There are already multiple solutions available that may match your specific problem. To give you some possible approaches to solve problems like this have a look at here are some links:




        • Is there a Threadsafe Observable collection in .NET 4?

        • Threadsafe ObservableCollection

        • BindingOperations.EnableCollectionSynchronization







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 8:03









        FruchtzwergFruchtzwerg

        6,603122836




        6,603122836
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463419%2fis-wpf-binding-to-concurrent-collections-safe%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini