1

I want to create a task to run a foo function for each item in the list. In the below code, let us say function Foo takes 20 seconds to run. By the time the task completes, the main thread would have exited the scope in which the task t was created. When the task t goes out of scope for the main thread, would the main thread delete the thread t?

void CreateTaskAndRun()
{
    ...doing something
    foreach(DummyClass obj in objList)
    {
        Task t = new Task(obj.Foo);
        t.Start(); //Foo takes 20 seconds to run
    }
    ...doing something
}
sgowd
  • 946
  • 3
  • 10
  • 27
  • 1
    A task is not a thread by itself. A task is a unit of work that can be processed by one of the threads in a managed thread pool. The end of a task is not the end of the thread, which will remain available for executing other tasks. Also, you can keep a reference to a task so you can await it and respond to it being done. If you don't do that, the task still exists and will still be executed. After it's done, I think its garbage collected like everything else. – GolezTrol Jun 19 '18 at 22:10
  • 3
    Quite some explanation about this, and some examples, can be found in [the lower half of the documentation on the Task class](https://msdn.microsoft.com/en-us/library/system.threading.tasks.task%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396#Remarks). – GolezTrol Jun 19 '18 at 22:13

1 Answers1

1

It depends on your application environment (e.g. ASP.NET, WPF, console app, etc.). In many types of applications, background tasks/threads will be killed once all the foreground tasks go out of scope. In those environments, it's a good idea to keep track of the tasks and make sure they all complete before allowing the main thread to close.

In some environments like ASP.NET, there are specific recommended ways to start a background task. These may pass a Cancellation Token into a callback delegate for the background task, so the environment can send a cancellation message to all the tasks that are still running when the server is about to shut down.

If you're writing a class library, you'll have to decide what's most appropriate: awaiting all the tasks yourself (maybe in a Task.WhenAll after they've all been started), or setting expectations with your API so the consumers can tie in their environment's shutdown events with your running tasks.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315