简体   繁体   English

创建任务时会发生什么?

[英]What happens when you create a Task?

public MyClass foo(int parameter)
{
    var foo = new Task<MyClass>(() => bar(parameter));

    try 
    {
        return foo.Result;
    }
}

What happens in terms of threads when I create a new Task . 当我创建一个new Task时,在线程方面会发生什么。

That means that new thread( B ) started to evaluate bar(parameter) and when the main thread( A ) goes to foo.Result; 这意味着新线程( B )开始评估bar(parameter)并且主线程( A )进入foo.Result; they wait until B finish and return Result ? 他们等到B完成并返回Result

From here : 这里

Tasks created by its public constructors are referred to as “cold” tasks, in that they begin their life cycle in the non-scheduled TaskStatus.Created state, and it's not until Start is called on these instances that they progress to being scheduled 由其公共构造函数创建的任务称为“冷”任务,因为它们在未计划的TaskStatus.Created状态下开始其生命周期,直到这些实例被调用Start才开始进行计划

Thus, no "thread B" will be started (moreover, " start new task" != " start new thread" in the general case). 因此,将不会启动“线程B”(此外,一般情况下为“ 开始新任务”!=“ 开始新线程”)。

and when the main thread(A) goes to foo.Result; 当主线程(A)进入foo.Result时; they wait until B finish and return Result? 他们等到B完成并返回结果?

Since there will be no "thread B", thread A will wait forever. 由于将没有“线程B”,因此线程A将永远等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM