简体   繁体   中英

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 .

That means that new thread( B ) started to evaluate bar(parameter) and when the main thread( A ) goes to foo.Result; they wait until B finish and return 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

Thus, no "thread B" will be started (moreover, " start new task" != " start new thread" in the general case).

and when the main thread(A) goes to foo.Result; they wait until B finish and return Result?

Since there will be no "thread B", thread A will wait forever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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