Из моего понимания ключевого слова async
использование await
в комбинации используется для создания точки продолжения, когда фактически требуется результат асинхронной операции, что позволяет выполнять другую работу в промежуточный период.
Тогда почему следующая блокировка?Я бы ожидал, что Nothing to do while the awaits complete, expecting this line to come first.
будет первой строкой вывода на консоль ..
In tasks.cs
public static async Task Execute()
{
var sw = new Stopwatch();
sw.Start();
await Foo();
sw.Stop();
Console.WriteLine($"Execute completed in {sw.ElapsedMilliseconds}ms.");
}
private static async Task Foo()
{
var tasks = Enumerable.Range(0, 5).Select(x =>
{
return Task.Factory.StartNew((b) =>
{
Thread.Sleep(100);
int value = (int) b;
Console.WriteLine($"Task ran on thread: {Thread.CurrentThread.ManagedThreadId}");
return value * value;
}, x);
}).ToArray();
await Task.WhenAll(tasks);
}
, которая вызывается в main
static async Task Main(string[] args)
{
await Tasks.Execute();
var result = await LongRunningOperation();
Console.WriteLine("Nothing to do while the awaits complete, expecting this line to come first.");
Console.WriteLine($"Long running operation result: {result}");
}
private static async Task<int> LongRunningOperation()
{
var sw = new Stopwatch();
sw.Start();
var res = await Task.Factory.StartNew(() =>
{
Thread.Sleep(10000);
Console.WriteLine($"Long running operation completed on thread {Thread.CurrentThread.ManagedThreadId}");
return 10000;
});
sw.Stop();
return res;
}
Что выводит следующее:
Task ran on thread: 7
Task ran on thread: 4
Task ran on thread: 3
Task ran on thread: 5
Task ran on thread: 6
Execute completed in 113ms.
Long running operation completed on thread 9
Nothing to do while the awaits complete, expecting this line to come first.
Long running operation result: 10000
Что означает, что я блокирую в этом контексте, и все последовательно соединены воедино ... что я не понимаю?