Answer the question
In order to leave comments, you need to log in
C# Portable Class Library async property, how to make the code straighter?
Greetings.
I want to create a class with asynchronous property getters. It seems to even work and work. There are only doubts about the beauty of the code, but the knowledge of how to make it more beautiful is not enough..
private double _d;
public double D
{
get
{
System.Threading.SynchronizationContext.Current.Post((s) =>
{
Action a = async () => { D = await getD(); };
a();
}, this);
return _d;
}
set
{
_d = value;
NotifyPropertyChanged("D");
}
}
private async Task<double> getD()
{
HttpClient hc = new HttpClient();
HttpResponseMessage resp = await hc.GetAsync("http://habr.ru");
string pageContent = await resp.Content.ReadAsStringAsync();
return pageContent.Length;
}
Answer the question
In order to leave comments, you need to log in
I don't really understand why you need an asynchronous getter.
Make an asynchronous method in the model that receives a value and puts it in a field associated with the UI. The method can be called in the constructor, or by a timer, or via a command - as needed.
If you don’t like that while loading is in progress, the default value is shown in the UI - there are already options, from the banal FallbackValue when linking to converters and custom fields (somehow for this purpose I made a field of the string type model, when loading asynchronously I entered the value there type "loading...", and after successful loading put the value formatted in string there).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question