Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy load properties with Async

I've learned to lazy load properties in my repository. Now I'd like to do that, but I also need to load something from a web page (using Httpclient) which means my property will be async.

public async Task<List<NewsModel>> News
{
    get
    {
        if (_news == null)
        {
            CacheProvider cache = new CacheProvider();
            object cachedNews = cache.Get("news");

            if (cachedNews == null)
            {
                var client = new HttpClient();
                // await HttpResponse
            }

        }
        return _news;
    }

    set
    {
        _news = value;
    }
}

However, visual studio is telling me that

"The modifier async is not valid for this item"

while highlighting the word "News" in the first line.

Is it possible to do this? Or do I have to write a separate method?

like image 353
Saturnix Avatar asked Jul 31 '13 16:07

Saturnix


1 Answers

Asynchronous properties are not supported. I describe a number of workarounds on my blog.

In your case, it sounds like asynchronous lazy initialization would be a good solution (also described on my blog).

like image 66
Stephen Cleary Avatar answered Sep 19 '22 15:09

Stephen Cleary