I built some async/await demo console app and get strange result. Code:
class Program
{
public static void BeginLongIO(Action act)
{
Console.WriteLine("In BeginLongIO start... {0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
act();
Console.WriteLine("In BeginLongIO end... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
}
public static Int32 EndLongIO()
{
Console.WriteLine("In EndLongIO start... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
Console.WriteLine("In EndLongIO end... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
return 42;
}
public static Task<Int32> LongIOAsync()
{
Console.WriteLine("In LongIOAsync start... {0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
var tcs = new TaskCompletionSource<Int32>();
BeginLongIO(() =>
{
try { tcs.TrySetResult(EndLongIO()); }
catch (Exception exc) { tcs.TrySetException(exc); }
});
Console.WriteLine("In LongIOAsync end... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
return tcs.Task;
}
public async static Task<Int32> DoAsync()
{
Console.WriteLine("In DoAsync start... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
var res = await LongIOAsync();
Thread.Sleep(1000);
Console.WriteLine("In DoAsync end... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
return res;
}
static void Main(String[] args)
{
ticks = DateTime.Now.Ticks;
Console.WriteLine("In Main start... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
DoAsync();
Console.WriteLine("In Main exec... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(3000);
Console.WriteLine("In Main end... \t\t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
}
private static Int64 ticks;
}
The result bellow:
Maybe I do not fully understand what exactly makes await. I thought if the execution comes to await then the execution returns to the caller method and task for awaiting runs in another thread. In my example all operations execute in one thread and the execution doesn't returns to the caller method after await keyword. Where is the truth?
Short answer is that LongIOAsync() is blocking. If you run this in a GUI program you will actually see the GUI freezes briefly - not the way async/await is supposed to work. Therefore the entire thing falls apart.
You need to wrap all the long running operations in a Task then directly await on that Task. Nothing should block during that.
To really understand this behaviour, you need to first understand what
Task
is and whatasync
andawait
actually do to your code.Task
is the CLR representation of "an activity". It could be a method executing on a worker-pool thread. It could be an operation to retrieve some data from a database over a network. Its generic nature allows it to encapsulate many different implementations, but fundamentally you need to understand that it just means "an activity".The
Task
class gives you ways to examine the state of the activity: whether it has completed, whether it has yet to start, whether it generated an error, etc. This modelling of an activity allows us to more easily compose programs which are built as a sequence of activities, rather than a sequence of method calls.Consider this trivial code:
What this means is "execute method
Foo
, then execute methodBar
. If we consider an implementation that returnsTask
fromFoo
andBar
, the composition of these calls is different:The meaning is now "Start a task using the method
Foo
and wait for it to finish, then start a task using the methodBar
and wait for it to finish." CallingWait()
on aTask
is rarely correct - it causes the current thread to block until theTask
completes and can cause deadlocks under some commonly-used threading models - so instead we can useasync
andawait
to achieve a similar effect without this dangerous call.The
async
keyword causes execution of your method to be broken down into chunks: each time you writeawait
, it takes the following code and generates a "continuation": a method to be executed as aTask
after the awaited task completes.This is different from
Wait()
, because aTask
is not linked to any particular execution model. If theTask
returned fromFoo()
represents a call over the network, there is no thread blocked, waiting for the result - there is aTask
waiting for the operation to complete. When the operation completes, theTask
is scheduled for execution - this scheduling process allows a separation between the definition of the activity and the method by which it is executed, and is the power in the use of tasks.So, the method can be summarised as:
Foo()
Bar
In your console app, you aren't awaiting any
Task
that represents the pending IO operation, which is why you see a blocked thread - there is never an opportunity to set up a continuation which would execute asynchronously.We can fix your LongIOAsync method to simulate your long IO in an asynchronous fashion by using the
Task.Delay()
method. This method returns aTask
that completes after a specified period. This gives us the opportunity for an asynchronous continuation.This isn't how
async-await
works.Marking a method as
async
doesn't create any background threads. When you call anasync
method it runs synchronously until an asynchronous point and only then returns to the caller.That asynchronous point is when you
await
a task that haven't completed yet. When it does complete the rest of the method is scheduled to be executed. This task should represent an actual asynchronous operation (like I/O, orTask.Delay
).In your code there is no asynchronous point, there's no point in which the calling thread is returned. The thread just goes deeper and deeper and blocks on
Thread.Sleep
until these methods are completed andDoAsync
returns.Take this simple example:
Here we have an actual asynchronous point (
Task.Delay
) the calling thread returns toMain
and then blocks synchronously on the task. After a second theTask.Delay
task is completed and the rest of the method is executed on a differentThreadPool
thread.If instead of
Task.Delay
we would have usedThread.Sleep
then it will all run on the same calling thread.the line that actually runs something on a background thread is
In your example you are not awaiting that Task but that of a TaskCompletionSource
When awaiting LongIOAsync you are awaiting the the task from tcs witch is set from a background thread in a delegate given to Task.Run()
apply this change :
Alternately in this case you could of just awaited the returned from Task.Run() , TaskCompletionSource is for situations where you want to pass around the ability to set your Task as complete or other wise.