[英]Does Task.Run() code execute asynchronously?
I have defined this block code. 我已经定义了此块代码。 Can anyone tell me if this code is asynchronous or parallel ?
谁能告诉我这段代码是异步的还是并行的 ? This block code just only an example.
此块代码仅是示例。 It creates four threads and in the end waits for all the threads to be complete.
它创建四个线程,最后等待所有线程完成。
public Form1()
{
InitializeComponent();
var t1 = Task.Run(() =>
{
GetSum();
});
var t2 = Task.Run(() =>
{
GetSum();
});
var t3 = Task.Run(() =>
{
GetSum();
});
var t4 = Task.Run(() =>
{
GetSum();
});
Task.WaitAll(t1, t2, t3, t4);
}
private int GetSum()
{
int sum = 0;
for (int i = 0; i < int.MaxValue; i++)
{
sum += i;
}
return sum;
}
First of all, a Task doesn't directly create a thread. 首先,任务不会直接创建线程。 A Task handles threads via the ThreadPool mechanism.
任务通过ThreadPool机制处理线程。 It is Asynchronous.
它是异步的。 This is because the static method Task.Run() returns a work queued to execute in the ThreadPool to it's caller.
这是因为静态方法Task.Run()将排队等待在ThreadPool中执行的工作返回给其调用者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.