Reputation: 101
I am starting to read about .NET 4.5 Async but frankly cannot get the most of it yet when to comes to the usage patter. So i will try to get that with a direct question:
I usually use .NET 4 TPL to call expensive Web services and DB calls from inside my ASP.NET application. Seems that i can achieve the same thing with Async. Is this true? When to use which?
Thanks in advance.
Upvotes: 10
Views: 4336
Reputation: 1080
@Pawan about the BeginXXX/EndXXX: I think you are mixing up the things. Looking onto C#, there are 3 different patterns of running parallel code:
TPL is the foundation, on which the TAP is built. TPL was introduced in .NET 4. Altough TPL and TAP are somehow used equally in the Microsoftdocumentation. Either way, the async/await is then only a language feature introduced with C# 5, means .NET 4.5, to give support for the TPL in a simplified way.
The BeginXXX/EndXXX belongs to the APM style! So it does not have anything to do with the TPL. These multiple versions make it difficult to keep the overview.
Upvotes: 0
Reputation: 10323
TPL is a library for parallel computing. .NET 4.5 async is a language feature, built on top of TPL, that makes the process easier. This is especially true when you have workflows with multiple steps.
In a nutshell, async
lets you write your code as if it were synchronous, so the logical flow remains intact. The process of waiting for a task to complete, running specific code when that happens, can be done in a very natural fashion with async
. The C# 5.0 and VB 11.0 compilers transform your code into the equivalent C# 4.0 and VB 10.0 code using TPL and some new async
related types.
For an excellent under-the-hood explanation of async
, see Jon Skeet's Eduasync blog series.
So, how do you decide which to use? Well, async
basically abstracts away all the complexities of creating a sequence of code fragments that are chained together with asynchronous calls. Presumably when you call a web service or access a database, you want to do something with what gets returned. async
allows you to put the calling and processing code together, which should make your code easier to write and also easier read later on.
Upvotes: 16
Reputation: 7268
My guess is internally both .Net TPL and async, uses threadpool threads. Async might be a simplified syntax for the conventional BeginXXX/EndXXX pattern.
But more importantly TPL uses, threadpool thread and you should not be using it for performing expensive operations as the same threads are used by framework itself. If you are having expensive operation(as you have mentioned) then its better to create a new stand alone thread or set the ThreadSchedular's "LongRunning" property to when using TPL.
Upvotes: -1