Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async / await with task.run vs task.run and continuewith in .NET 4.0

I have installed async package in .net 4.0. this gives me the ability to use async / await keywords in my applications.

as i have understood until now i can use wrap my task.run code in async / await and have the same result as using task.run with continuewith.

Is this true? or there are deeper differences?

like image 200
e4rthdog Avatar asked Dec 05 '12 07:12

e4rthdog


People also ask

What is difference between async and Task C#?

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

What is Task run async?

In . NET, Task. Run is used to asynchronously execute CPU-bound code. Let's say there is a method which does some CPU-bound work. Example : looping through a large array and doing some complex computation on each element of the array.

What is difference between async and await in C#?

An async keyword is a method that performs asynchronous tasks such as fetching data from a database, reading a file, etc, they can be marked as “async”. Whereas await keyword making “await” to a statement means suspending the execution of the async method it is residing in until the asynchronous task completes.

Which is the recommended way to wait for an async method to complete?

No problem, just make a loop and call this function with an await: [code] for (int i = pendingList. Count - 1; i >= 0; i--)


1 Answers

It depends on what you're doing with ContinueWith. But yes, often you can use await to achieve the same effects you'd previously have achieved using ContinueWith. What you can't do is things like "continue with this code only on failure" - you just use normal exception handling for that. As AlexH says, there will be further differences in terms of the overall behaviour of your async method - but in most cases I'd say that's desirable. Basically, the asynchrony of the code flows, so async methods tend to call more async methods, etc.

I suggest you read up on what async/await is about (there are loads of resources out there - I'd recommend the "Consuming the Task-based Asynchronous Pattern" page on MSDN as one starting point.

like image 168
Jon Skeet Avatar answered Nov 15 '22 17:11

Jon Skeet