Let's suppose I have a long running Web API call (async method) which returns a string.
Is there a best practice between those 2 solutions to display the result in a WPF property without blocking UI ? Or is there another one ?
Note: both solutions are not freezing UI and I already view posts How to call an async method from a getter or setter? and Async property in c#.
My Wep API
private async Task<string> GetAsyncProperty()
{
string result = "Async Property Value";
// Web api call...
await Task.Delay(TimeSpan.FromSeconds(10));
return result;
}
Solution A
XAML:
<TextBlock Text="{Binding Path=AsyncPropertyA, UpdateSourceTrigger=PropertyChanged}" />
ViewModel:
public MyConstructor()
{
Task task = SetAsyncPropertyA();
}
private async Task SetAsyncPropertyA()
{
this.AsyncPropertyA = await GetAsyncProperty().ConfigureAwait(false);
}
Solution B
XAML:
<TextBlock Text="{Binding Path=AsyncPropertyB, UpdateSourceTrigger=PropertyChanged, IsAsync=True, FallbackValue='Loading B...'}" />
ViewModel:
public string AsyncPropertyB
{
get
{
return GetAsyncPropertyB();
}
}
private string GetAsyncPropertyB()
{
return Task.Run(() => GetAsyncProperty()).Result;
}
Note: in solution B, I can add FallbackValue that's not working in solution A and potentially some other UI updates in ContinueWith of the Task.Run.