This question already has an answer here:
- How to call async method in constructor? 4 answers
I've added a call to an asynchronous method in my constructor, in order to initialize data for the ViewModel when loaded.
But I noticed there is a warning on the calling of that method in the VM constructor. It states that "this call is not awaited"
I understand from this error that the call needs to be prefixed with await
. but this would also mean that the constructor would have to be marked as an async Task
which I know it can't be in C#. As constructors can't be async.
Does anyone have an example, of how to refactor the call out of the constructor? Or what implementation pattern to use instead?
This is a summarized version of the ViewModel, showing how I call the method in the constructor:
namespace MongoDBApp.ViewModels
{
[ImplementPropertyChanged]
public class CustomerDetailsViewModel
{
private IDataService<CustomerModel> _customerDataService;
private IDataService<Country> _countryDataService;
public CustomerDetailsViewModel(IDataService<CustomerModel> customerDataService, IDataService<Country> countryDataService)
{
this._customerDataService = customerDataService;
this._countryDataService = countryDataService;
//warning about awaiting call, shown here...
GetAllCustomersAsync();
}
#region Properties
public ObservableCollection<CustomerModel> Customers { get; set; }
public ObservableCollection<Country> Countries { get; set; }
#endregion
#region methods
private async Task GetAllCustomersAsync()
{
var customerResult = await _customerDataService.GetAllAsync();
Customers = customerResult.ToObservableCollection();
var countryResult = await _countryDataService.GetAllAsync();
Countries = countryResult.ToObservableCollection();
}
#endregion
}
}
Aucun commentaire:
Enregistrer un commentaire