Anker Peet
Anker Peet

Reputation: 51

When does a C# Task terminate?

I am working with ASP.NET. When I run a new Task, at what point will that Task terminate? Will it terminate when the thread that called it terminates? Or will it continue on until it has finished running the code within my lambda expression?

Here is an example of what I am trying to do:

Task.Run(() =>
{
    try
    {
        MyFunction();
    }
    catch (Exception ex)
    {
        Console.Write(ex);
    }
});

MyFunction() does not return anything, I simply want it to start running on its own so that the current thread can continue. When I run my application and call this code, it seems to work just fine. I am just trying to see if I should be worried about the task spontaneously terminating or if I will be just fine.

I also should mention that the thread that makes the request is probably going to terminate before the Task finishes.

Thanks.

Upvotes: 0

Views: 2330

Answers (2)

Michael Puckett II
Michael Puckett II

Reputation: 6749

A Task may or may not have a thread but in your case of Task.Run it should. You can reference the Task itself and it will live as long as it's in scope or you keep a living reference to it. The thread it runs against will continue until the code completes. It's a little confusing but know that the Task itself and the running thread are seperate. A Task, is more like the state / manager of some work, which may or may not be on a seperate thread. This reference can be held until the application terminates if desired where you can read the state of the work, even if it's complete.

If the Task leaves the scope and there is no reference the unit of work it monitors will continue; however the Task itself will be setup for garbage collection when this is complete. In other words, you can fire and forget the Task if you want and unless there is an error or you end the application the unit of work assigned to the Task will complete.

Note that a Task will terminate with your application and if that Task does spawn a new thread such as you are doing with Task.Run it will also terminate with your application if the application ends.

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81493

  1. The task finishes its life soon after it finishes executing the code it was tasked with.

  2. When the task falls out of scope it will eventually be cleaned up by the garbage collector, providing there is no code left to execute

Lastly there is no good reason why tasks should end abruptly unless an exception is thrown and cannot be caught.

.net. Doesn't roll a dice to terminate the task otherwise they would be useless. They live as long as they need to live and terminate soon after

Technically this will use a thread pool thread and it's returned to the pool, however they are just semantics

https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming

Upvotes: 3

Related Questions