Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using only async Task and Task?

For example, the difference between this code

public Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
    {
        var result = _conf.BasePath
            .AppendPathSegment("news-sentiment-indexes")
            .SetQueryParams(new
            {
                from = from.ToString("s"),
                to = to.ToString("s"),
                grouping
            });

        return result
           .GetStringAsync()
           .ContinueWith(Desereialize<IList<NewsSentimentIndexes>>);
    }

and that

 public async Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
    {
        var result = _conf.BasePath
            .AppendPathSegment("news-sentiment-indexes")
            .SetQueryParams(new
            {
                from = from.ToString("s"),
                to = to.ToString("s"),
                grouping
            });

        var newsStr =  await result.GetStringAsync();
        return JsonConvert.DeserializeObject<NewsSentimentIndexes>(newsStr);
    }

Which one is correct or faster working? And just call this method need to await or just a task ?

like image 768
Gleb Patcia Avatar asked Jun 18 '16 05:06

Gleb Patcia


2 Answers

The async one is better. You should always prefer to use await instead of ContinueWith. I go into the details of why ContinueWith is bad on my blog.

The semantic differences between these two implementations are due to two differences: whether or not async is used, and whether or not ContinueWith is used.

Removing async changes exception semantics. When async is used, any exceptions are caught (by the compiler-generated state machine) and placed on the returned task. Without async, exceptions are raised directly (synchronously). So, if BasePath, AppendPathSegment, SetQueryParams, or GetStringAsync throw (or return null or anything like that), then that exception would be raised synchronously rather than asynchronously, which could be confusing to callers.

Using ContinueWith changes execution semantics. In this case, Deserialize will be scheduled on TaskScheduler.Current. This dependence on the current TaskScheduler is one of the trickiest parts of ContinueWith.

like image 124
Stephen Cleary Avatar answered Sep 23 '22 06:09

Stephen Cleary


Both methods returns same type: Task. But async method allows to use await keyword in his body. It informs compiler to generate state machine for await and its all. About async/await performance you can read this post

like image 20
Kirill Avatar answered Sep 23 '22 06:09

Kirill