Handle leak in C#'s Task class??

Asked 2 years ago, Updated 2 years ago, 114 views

Hello.

I am currently studying C#, but I am writing a thread program using the Task class.
I make a lot of threads in the Task class and look at the number of handles in Task Manager, but it keeps increasing and doesn't decrease even after the thread finishes.Here's the code:

static void Main (string[]args)
    {
        var tasks = new List <Task <int >>();

        Console.WriteLine("Start");
        Console.ReadLine(); // The number of handle is 180

        // Define a delete that prints and returns the system tick count
        Func<object,int>action=(object objectj)=>
        {
            inti=(int)obj;

            // Make each thread sleep a different time in order to return a different tick count
            Thread.Sleep(i%100);

            Console.WriteLine("{0}", i);
            returni;
        };

        // Construct started tasks
        for (inti=0; i<5000;i++)
        {
            int index=i;
            tasks.Add (Task<int>.Factory.StartNew(action, index));
        }

        Console.WriteLine("Add end");
        Console.ReadLine(); // The number of handle is 312

        // Wait for all the tasks to finish.
        Task.WaitAll(tasks.ToArray());

        // We should never get to this point
        Console.WriteLine("WaitAll() has not done exceptions.THIS WAS NOT EXPECTED.");

        Console.WriteLine ("Test END");
        Console.ReadLine(); // The number of handle is 312

    }

I've seen on my MSDN blog or somewhere that it says that there is no problem not to run Dispose for Tasks, but the number of handles does not change when you run Dispose.It's very disgusting that the steering wheel does not decrease while increasing, but at first glance, it looks like a steering wheel leak.
I have to write a program that generates a lot of threads using Task, but honestly, I'm scared that the number of handles seems to increase indefinitely.Does anyone know if it's okay to leave it as it is or if there's a prescription for it? I'm wondering if it's okay to leave it as it should be because the upper limit on the number of handles has been set.

c# .net

2022-09-30 21:29

1 Answers

The Task class internally uses ThreadPool, which is a pool and is left to retain the completed thread in anticipation of the need for more, naturally, many boots.
In addition, the Task class is a class that retains processing and results, so invoking Dispose is independent of the thread on which the process was performed and does not recover the thread and its handle.

Therefore, I hope you will understand that it is properly managed by the thread pool.You can also create this derivative class and customize its behavior by providing the TaskScheduler class for better management.


2022-09-30 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.