【发布时间】:2021-03-01 22:27:55
【问题描述】:
我知道您应该尽量不要使用async void,事件处理程序除外。事件处理程序的例外是否包括 Prism 事件?我下面的例子可以吗?
模块 A 的视图有一个 DataGrid,当用户单击记录时它会发布 SelectionChangedEvent,该事件在模块 B 中订阅,可能需要一段时间才能完成。
public class ModuleA
{
private ObservableCollection<Company> carCollectionOC = new ObservableCollection<Company>();
private void CarCollection_CurrentChanged(object sender, EventArgs e)
{
Company company = (Company)(sender as ICollectionView).CurrentItem;
this.eventAggregator.GetEvent<SelectionChangedEvent>().Publish(company.Brand);
}
}
模块 B 订阅并执行async void。
public class ModuleB
{
private ObservableCollection<Vehicle> vehicleOC = new ObservableCollection<Vehicle>();
private VehicleService vehicleService;
public ModuleB(IEventAggregator eventAggregator)
{
this.vehicleService = new VehicleService();
this.eventAggregator.GetEvent<SelectionChangedEvent>()
.Subscribe(this.SubscribedMethod,
ThreadOption.UIThread,
false);
}
private async void SubscribedMethod (string brand)
{
this.vehicleOC = await this.GetData(brand);
}
private List<Vehicle> GetVehicles(string carBrand)
{
Console.WriteLine("finishing GetVehicles");
return this.vehicleService.GetVehicleList(carBrand);
}
private async Task<ObservableCollection<Vehicle>> GetData(string carBrand)
{
vehicleListFromService = await Task.Run(() => this.GetVehicles(carBrand));
this.vehicleOC.Clear();
foreach (var vehicle in vehicleListFromService)
this.vehicleOC.Add(vehicle);
return this.vehicleOC;
}
}
【问题讨论】:
-
Subscribe中使用的方法不是订阅方法,而是订阅方法。订阅的是一个事件。因此,事件聚合器。
标签: c# wpf async-await prism