我使用Visual Studio 2015和Entity Framework 6構建MVVM Light WPF應用程序。當用戶點擊搜索按鈕,它調用已在視圖模型的構造函數中定義這樣的RelayCommand
:執行異步搜索,返回ObservableCollection
SearchEmployeesRelayCommand = new RelayCommand(SearchEmployees);
在視圖模型的SearchEmployees
方法是這樣的:
private BackgroundWorker _worker;
public void SearchEmployees()
{
_worker = new BackgroundWorker(); // use this to show busy indicator
var dataService = new EmployeeDataService();
_worker.DoWork += (o, ea) =>
{
SearchResults = dataService.SearchEmployees(SelectedColumn, SearchValue);
};
_worker.RunWorkerCompleted += (o, ea) =>
{
IsSearching = false;
};
IsSearching = true;
_worker.RunWorkerAsync();
}
的數據服務的搜索方法是這樣的:
public ObservableCollection<EmployeeViewModel>
SearchEmployees(string selectedColumn, string searchValue)
{
var paramEmployee = Expression.Parameter(typeof(Employee), "e");
var comparison = Expression.Lambda<Func<Employee, bool>>(
Expression.Equal(
Expression.Property(paramEmployee, selectedColumn),
Expression.Constant(searchValue)),
paramEmployee).Compile();
using (var context = new MyEntities())
{
var query = (from e in context.Employees
.Where(comparison)
select new EmployeeViewModel
{
// Various EF model properties...
});
return new ObservableCollection<EmployeeViewModel>(query);
}
}
如果我儘量讓上面的方法async
和awaitable
,像這樣的東西:
return await new ObservableCollection<EmployeeViewModel>(query);
它給這個錯誤:
'ObservableCollection' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'ObservableCollection' could be found (are you missing a using directive or an assembly reference?)
你如何使搜索async
如果它返回一個ObservableCollection
?謝謝。
更新:對於忙碌的指示工作,我不得不做出這個改變:
_worker.DoWork += async (o, ea) =>
{
SearchResults = await dataService
.SearchEmployees(selectedColumnValue, SearchValue);
IsSearching = false;
};
我完全刪除了_worker.RunWorkerCompleted
塊。有可能有更好的方法來做到這一點,但這是我得到它的工作原理。
您需要閱讀此https://msdn.microsoft.com/en-us/library/hh191443.aspx – Will