mercredi 6 mai 2015

Is Task.Run or Task.Factory.StartNew a bad practice for windows phone or any other client platform?

I have WP 8.1 app that using web service a lot, and I want to keep it as much responsive as possible. From iOS dev expierense - there is one strict rule: "Do not do in UI thread any complex calculations! Doesnt matter how you will reach this: with blocks or with GCD".

Problem that not all API has async versions, e.g. JSON.NET, SQLite or any own complex algorithm in the app. I have read a lot of articles that are defining Task.Run and Task.Factory.StartNew as bad practice + this.

So, is it good to write code like this? Will it cause some cpu overloading/battery drain or some another performance issues? And if not - what is the right way to make complex operations async(background thread)?

 protected async Task<T> GetDataAsync<T>(string uriString, CancellationToken cancellationToken = default(CancellationToken))
    {
        var uriToLoad = new Uri(uriString);
        using (var httpClient = new HttpClient())
        {
            var data = await httpClient.GetAsync(uriToLoad, cancellationToken).ConfigureAwait(false);
            data.EnsureSuccessStatusCode();
            cancellationToken.ThrowIfCancellationRequested();

            var dataString = await data.Content.ReadAsStringAsync();
            cancellationToken.ThrowIfCancellationRequested();

            // async wrapped call to sync API
            var result = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(dataString), cancellationToken).ConfigureAwait(false);
            cancellationToken.ThrowIfCancellationRequested();

            return result;
        }
    }

Aucun commentaire:

Enregistrer un commentaire