Swi*_*ter 5 c# wpf asynchronous listbox async-await
我有一个 ListBox 并且想将它的 ItemsSource 设置为我从云中获取的 ObservableCollection。我必须等待这个传入的集合,它导致我的 itemssource 没有更新。
这是我的方法。这是我的 xaml.cs 构造函数:
{
InitializeComponent();
GetEmployeeList();
}
Run Code Online (Sandbox Code Playgroud)
以及它调用的方法:
private async void GetEmployeeList()
{
await EmployeeController.GetAllEmployees().ContinueWith(r =>
{
_employees = (r.Result);
EmployeeListBox.ItemsSource = _employees;
});
}
Run Code Online (Sandbox Code Playgroud)
我的 EmployeeController.GetAllEmployees() 返回一个 ObservableCollection。并且 _employees 得到更新,但是我的 EmployeeListBox 没有显示这些对象。我曾尝试使用静态硬编码集合,它运行良好 - 是因为我的异步吗?有人有建议吗?
- 谢谢。
假设您确定 continueWith 正在被调用,则很可能您的 continueWith 代码块发生在非 UI 线程上。
一种选择是为延续设置 CurrentSyncronizationContext(如下例)。这要求延续代码在原始任务启动的同一线程上执行。或者,您需要调用 UI 线程上的代码,最常见的是使用 Dispatcher。
private async void GetEmployeeList()
{
await EmployeeController.GetAllEmployees().ContinueWith(r =>
{
_employees = (r.Result);
EmployeeListBox.ItemsSource = _employees;
},
TaskScheduler.FromCurrentSynchronizationContext());
}
Run Code Online (Sandbox Code Playgroud)
但是,由于您使用的是等待 - 并且是从 UI 线程调用的,因此您也可以将等待的结果直接设置为 ItemSource:
private async void GetEmployeeList()
{
EmployeeListBox.ItemsSource = await EmployeeController.GetAllEmployees();
}
Run Code Online (Sandbox Code Playgroud)
...这也很好地演示了 async/await 关键字节省了您编写多少代码:)