I built some async/await demo console app and get strange result. Code:
class Program
{
public static void BeginLongIO(Action act)
{
Console.
the line that actually runs something on a background thread is
Task.Run( () => { } );
In your example you are not awaiting that Task but that of a TaskCompletionSource
public static Task LongIOAsync()
{
var tcs = new TaskCompletionSource();
Task.Run ( () => BeginLongIO(() =>
{
try { tcs.TrySetResult(EndLongIO()); }
catch (Exception exc) { tcs.TrySetException(exc); }
}));
return tcs.Task;
}
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 :
public static Task LongIOAsync()
{
Console.WriteLine("In LongIOAsync start... {0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
var tcs = new TaskCompletionSource();
Task.Run ( () => 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;
}
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.