What is the difference between using only an asynchronous task and a 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>>); } 

So what

  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? And just call this method need to wait or just complete the task?

+8
c # asynchronous parallel-processing task-parallel-library task
source share
3 answers

async better. You should always use await instead of ContinueWith . I go into details why ContinueWith bad on my blog.

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

Removing async changes the semantics of exceptions. When async used, any exceptions are caught (by the state machine generated by the compiler) and placed in the returned task. Without async exceptions occur directly (synchronously). So, if BasePath , AppendPathSegment , SetQueryParams or GetStringAsync throw (or return null or something like that), then this exception will be generated synchronously and not asynchronously, which can confuse callers.

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

+6
source share

Both methods return the same type: Task . But the async method allows you to use the await keyword in your body. It tells the compiler to create a state machine for await and all of it. About async / await performance you can read this post

+5
source share

Async Task returns an object, but Task does not.

So you can do this with the Async task:

 var yourTask = AsyncTask() 

so far you can do this with the usual task:

 NormalTask().someFunction() 
-3
source share

All Articles