现在您正在分配response
的结果在某些方面Task.Run
还需要完成。Task
这在编译时会自动发生,因为您使用的是关键字await
。
如果您愿意,您可以分配response
给跑步Task
本身并继续前进。我当然不会再叫它response
了。假设您这样做并task1
改为调用它。
var task1 = Task.Run(()=>CreateData());
现在您的代码将继续运行,并且task1
仅代表正在运行的Task
.
如果你有 5 个,你可以按照你想要的那样做。
var task1 = Task.Run(()=>CreateData());
var task2 = Task.Run(()=>CreateData());
var task3 = Task.Run(()=>CreateData());
var task4 = Task.Run(()=>CreateData());
var task5 = Task.Run(()=>CreateData());
Now you can also wait for all of these tasks to complete at the same time with Task.WhenAll
method.
await Task.WhenAll(task1, task2, task3, task4, task5);
So to sum it up.
The await
keyword does some compiler magic and basically puts a callback in that place of the method (assigning the rest of the method to be a continuation when the Task
is complete) and ALSO assigns the Result
of that Task
to the variable (if the Task
has a result). There is a lot to unpack here; I don't believe a short answer really justifies what's happening.
Without using the await
keyword then you simply assign the Task
itself to the variable.