Ads Top

Update UI Thread with async and await

While working in WPF you may have to encounter an issue in updating UI of application. I've got through this and make a solution.
I've used two fictions to demonstrate this updateList() is an async function so that it can run in background and do not harm UI in other words if u use async and await, user will be able to minimize its application. Lets come to the point.

In other function addItemsToList()     I used a for loop and try to update UI while adding items in the list I got this error


Reason: because I am using async and await simple I just change addItemsToList() to this

this.Dispatcher.Invoke((Action)(() =>
                    {
                        listbox1.Items.Add("This is item: " + i);
                        listbox1.UpdateLayout();
                    }
                    ));
and its all good. Below here is the complete code.

private void button1_Click(object sender, RoutedEventArgs e)
        {
            updateList();
        }
        private void updateList()
        {
            await Task.Factory.StartNew(() =>
            {
                addItemsToList();
            }
             );

        }

        private void addItemsToList()
        {
            for (int i = 0; i <  1000   ; i++)
            {
                this.Dispatcher.Invoke((Action)(() =>
                    {
                        listbox1.Items.Add("This is item: " + i);
                        listbox1.UpdateLayout();
                    }
                    ));
               
            }
        }

No comments:

Powered by Blogger.