AFAIK - ( and I read a lot about it), asynchronous methods (not asynchronous delegates !) exists to solve the \"thread is blocked\" problem when
Task<T>
is not related to the I/O blocking issue. It is simply just like open a thread (plus extra efficiency and functionality) - but it still causes a thread to consume CPU quanta etc.
Not necessarily. Basically there are two kinds of Task
s: one executes a synchronous piece of code and completes when that code finishes executing. This kind of Task
blocks a Thread
the whole time since it starts executing until it's completed (successfully or not).
But there is another kind of Task
: one that completes when something happens. This kind of Task
is what .Net 4.5 and C# 5.0 use heavily and it doesn't block a Thread
(at least not directly). You can create such Task
yourself by using TaskCompletionSource<T>
.
(Another point is that a blocked thread doesn't consume any CPU, but that's not really relevant here.)
Is it just like creating a
Task<t>
withContinueWith
?
Yes, await t
is quite similar to t.ContinueWith(rest of the method)
.
Doesn't the terminology is confusing? Asynchronous methods are for I/O operations (where there are zero threads waiting while I/O operation is made and no thread is dealing with it). But to call a code (which use async) as: asynchronous methods is a bit confusing. Don't you think? Because I assume there is another thread which is executing.
I don't see the confusion. Classic asynchronous method (like BeginRead()
; this is called “Asynchronous Programming Model” or APM) is a way of starting an operation and being notified when it completes (though a callback). Modern async method (like ReadAsync()
; this is called “Task-based Asynchronous Pattern” or TAP) is also a way of starting an operation and being notified when it completes (using await
).
In both cases, there can be some code that executes before the method returns (the code before the first await
in the TAP case).
In both cases, the usual way of being notified about the result doesn't block any threads (callback for APM, await
for TAP).
In both cases, you can use blocking wait if you want (immediately calling the EndXxx()
method for APM, Wait()
for TAP).
Both cases can be used to execute synchronous code on a background thread (BeginInvoke()
on a delegate for APM, Task.Factory.StartNew()
for TAP).
Again, I don't see the confusion, the two models seem very similar to me.
Async methods are not just for IO - they can be for anything - and yes, it's just another way of saying that the work of the method is executed in a separate thread. Any method where the calling thread offloads the work to a separate thread can be correctly called an "async" method. It is the same as Task<T>
and ContinueWith
-- ContinueWith
is just another way of talking about a callback, really.
The word "asynchronous" simply means "not at the same time" - it can refer to any actions that happen independently of each other.