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 ?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With