Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF updating the itemssource in a ListBox with an async method

I have a ListBox and wanting to set its ItemsSource to an ObservableCollection that I get from my cloud. I have to await this incoming collection and it is causing my itemssource not to be updated.

This is my approach. This is my xaml.cs constructor:

{
    InitializeComponent();
    GetEmployeeList();
}

And the method it calls:

private async void GetEmployeeList()
{
    await EmployeeController.GetAllEmployees().ContinueWith(r =>
    {
        _employees = (r.Result);
        EmployeeListBox.ItemsSource = _employees;
    });
}

My EmployeeController.GetAllEmployees() returns an ObservableCollection. and _employees gets updated, however my EmployeeListBox doesn't show these objects. I have tried with a static hard coded collection and it works fine - so is it due to my async? Anyone got a suggestion?

- Thanks.

like image 514
Swidtter Avatar asked Oct 19 '22 21:10

Swidtter


1 Answers

Assuming you're sure the continueWith is being called, It's likely your continueWith code block is happening on a none-UI thread.

One option is to set the CurrentSyncronizationContext for the continuation (example below). This asks the continuation code to execute on the same thread that the original task was started from. Or alternatively, you need to invoke the code on the UI thread, most commonly using the Dispatcher.

private async void GetEmployeeList()
{
   await EmployeeController.GetAllEmployees().ContinueWith(r =>
   {
       _employees = (r.Result);
       EmployeeListBox.ItemsSource = _employees;
   },
   TaskScheduler.FromCurrentSynchronizationContext());
}

However, since you're using an await - and that is being called from a UI thread, you may as well set the result of the await to the ItemSource direct:

private async void GetEmployeeList()
{
   EmployeeListBox.ItemsSource = await EmployeeController.GetAllEmployees();
}

... Which is also a nice demonstration of how much code the async/await keywords save you having to write :)

like image 185
olitee Avatar answered Oct 22 '22 09:10

olitee