L
L
llexus2015-01-12 19:24:36
Windows phone
llexus, 2015-01-12 19:24:36

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;
        }

Is it possible to somehow call Action here without creating it? I would immediately call it in one line, so that it looks more impressive;)
And the second question, stupid: how can you "count" this property without assigning it to something.
That is just
oD;
instead
of double a = oD;
So it is read at the first binding to the guy, but if I want to refresh, I don’t know how to make it prettier ..
Well, or generally dissuade me from this crazy idea and offer more interesting options :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Papin, 2015-01-14
@i_light

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 question

Ask a Question

731 491 924 answers to any question