Can .NET Task instances go out of scope during run?

前端 未结 2 742
悲&欢浪女
悲&欢浪女 2020-11-30 06:33

If I have the following block of code in a method (using .NET 4 and the Task Parallel Library):

var task = new Task(() => DoSomethingLongRunning());
task.         


        
2条回答
  •  野性不改
    2020-11-30 07:09

    Update:

    After I answered this question (a long time ago!) I found out that it's not true that Tasks will always run to completion - there's a small, let's say "corner" case, where tasks may not finish.

    The reason for that is this: As I have answered previously, Tasks are essentially threads; but they are background threads. Background threads are automatically aborted when all foreground threads finish. So, if you don't do anything with the task and the program ends, there's a chance the task won't complete.

    You should always await on tasks. More information can be found on the excellent answer Jon gave me.


    Original:

    Task are scheduled to the ThreadPool, meaning that they are essentially threads¹ (actually, they encapsulate threads).

    From the Thread documentation:

    It is not necessary to retain a reference to a Thread object once you have started the thread. The thread continues to execute until the thread procedure is complete.

    So, no, there is no need to retain a reference to it.

    Also, the documentation states that the preferred way to create a Task is to use it's factory:

    You can also use the StartNew method to create and start a task in one operation. This is the preferred way to create and start tasks if creation and scheduling do not have to be separated (...)

    Hope it helps.


    ¹ Accordingly to the documentation:

    A task represents an asynchronous operation, and in some ways it resembles the creation of a new thread or ThreadPool work item, but at a higher level of abstraction.

提交回复
热议问题