【发布时间】:2015-10-12 09:24:08
【问题描述】:
我构建了一些 async/await 演示控制台应用程序并得到了奇怪的结果。代码:
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 关键字之后执行不会返回到调用方方法。 真相在哪里?
【问题讨论】:
-
你可以看这个:https://channel9.msdn.com/Shows/Going+Deep/Mads-Torgersen-Inside-C-Async
-
I thought if the execution comes to await then the execution returns to the caller method and task for awaiting runs in another thread.我所知道的每一个async简介(包括mine)都会特意明确说明这不是会发生什么。
标签: c# .net asynchronous async-await c#-5.0