我建立了一些异步/等待示例控制台应用程序并获得了奇怪的结果。代码:
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;
}
下面是结果:
以下是结果:
也许我没有完全理解await的作用。我认为,如果执行到了await,那么执行就会返回给调用方法,并且等待任务在另一个线程中运行。在我的例子中,所有操作都在一个线程中执行,并且在await关键字之后,执行不会返回给调用方法。 真相何在?
async
介绍(包括我的)都会特别明确地说明这不是发生的事情。 - Stephen Cleary