We have a largish WPF MVVM app which gets its data from web-servers via WCF services. To keep everything dynamic, all calls to the web services are asynchronous using async-await and Tasks. Although the app is generally very stable with hundreds of users across many dozens of installations, we do get occasional but persistent unhandled exceptions which are irritating, so I'm trying to spot potential weak spots in the code.
One possible issue is the following. We have a consistent pattern for data retrieval in our ViewModels (in C# pseudo code):
Code: Select all
// this is called from a RelayCommand when the user presses the search button
private void SearchForData()
{
this.FetchData();
}
private async void FetchData()
{
// this calls a method using Task.Factory.StartNew and returns Task<T>
List<T> mydatalist = await _dataservice.FetchDataFromWCFServiceAsync()
// MyDataBoundCollection is a property bound to a grid in the View
MyDataBoundCollection = new ObservableCollection<T>(mydatalist);
}
However note the method signature - async void. Researching I find this is a big no-no as async void methods can't handle normal try-catch error handling, and any error in the method will escalate up as an unhandled exception. After a fair amount of research I've come up with the following refactoring:
Code: Select all
private void SearchForData()
{
Task.Run(async ()=> await this.FetchDataAsync());
}
private async Task FetchDataAsync()
{
// now I can use try-catch as normal
try
{
List<T> mydatalist = await _dataservice.FetchDataFromWCFServiceAsync()
MyDataBoundCollection = new ObservableCollection<T>(mydatalist);
}
catch
{
}
}
Any thoughts or feedback gratefully accepted.
Nick