WPF loading animation on a separate UI thread? (C#)

前端 未结 2 1996
孤街浪徒
孤街浪徒 2020-12-02 00:11

Okay, I have a loading animation that runs while a large DataTable is populated to let the user know that the program has not frozen. I have the animation working fine, but

2条回答
  •  伪装坚强ぢ
    2020-12-02 00:52

    I wrote a little test program which shows the use of the Dispatcher class. It just requires a WPF-Window and a ListBox with Name "listBox". Should be easy to apply this solution to your problem.

        public void Populate() {
            // for comparison, freezing the ui thread
            for (int i = 0; i < 1000000; i++) {
                listBox.Items.Add(i);
            }
        }
    
        private delegate void AddItemDelegate(int item);
        public void PopulateAsync() {
            // create a new thread which is iterating the elements
            new System.Threading.Thread(new System.Threading.ThreadStart(delegate() {
                // inside the new thread: iterate the elements
                for (int i = 0; i < 1000000; i++) {
                    // use the dispatcher to "queue" the insertion of elements into the UI-Thread
                    // DispatcherPriority.Background ensures Animations have a higher Priority and the UI does not freeze
                    // possible enhancement: group the "jobs" to small units to enhance the performance
                    listBox.Dispatcher.Invoke(new AddItemDelegate(delegate(int item) {
                        listBox.Items.Add(item);
                    }), System.Windows.Threading.DispatcherPriority.Background, i);
                }
            })).Start();
        }
    

提交回复
热议问题