我在 AsyncDemoViewModel 中打印出 Messages 属性字符串列表。
如果我在 GetVideosSlowlyAsync() 中使用 Thread.Sleep(1000) 输出是
Time spent: 4001 milliseconds
- Started on thread 18, finished on thread 18
- Started on thread 18, finished on thread 18
- Started on thread 18, finished on thread 18
- Started on thread 18, finished on thread 18
如果我在 GetVideosSlowlyAsync() 中使用 await Task.Delay(1000) 输出是
Time spent: 4053 milliseconds
- Started on thread 12, finished on thread 19
- Started on thread 19, finished on thread 16
- Started on thread 16, finished on thread 19
- Started on thread 19, finished on thread 9
为什么等待调用没有释放调用线程?我预计 await 版本的完成时间会快 4 倍。
控制器代码:
public class AsyncDemoController : Controller
{
private DepartmentDb _db;
public AsyncDemoController(DepartmentDb db)
{
_db = db;
}
public async Task<ActionResult> Index()
{
var sw = Stopwatch.StartNew();
var v1 = await GetVideosSlowlyAsync();
var v2 = await GetVideosSlowlyAsync();
var v3 = await GetVideosSlowlyAsync();
var v4 = await GetVideosSlowlyAsync();
var vm = new AsyncDemoViewModel() {Videos = v1.Item2, Messages = new List<string>()};
sw.Stop();
vm.Messages.Add(string.Format("Time spent: {0} milliseconds", sw.ElapsedMilliseconds));
vm.Messages.Add(v1.Item1);
vm.Messages.Add(v2.Item1);
vm.Messages.Add(v3.Item1);
vm.Messages.Add(v4.Item1);
return View(vm);
}
private async Task<Tuple<string, IEnumerable<Video>>> GetVideosSlowlyAsync()
{
var t1 = Thread.CurrentThread.ManagedThreadId;
await Task.Delay(1000); // Thread.Sleep(1000);
var t2 = Thread.CurrentThread.ManagedThreadId;
return Tuple.Create(string.Format("Started on thread {0}, finished on thread {1}", t1, t2), _db.Videos.AsEnumerable());
}
}