2

recently i got confused with Task and Thread pool, given the follow codes:

    static void Main(string[] args)
    {
        while (true)
        {
            Thread.Sleep(1);
            Task t = new Task(run);
            t.Start();

        }
    }
    static void run()
    {
        Console.WriteLine(DateTime.Now);
        Thread.Sleep(1000 * 3600);
        Console.WriteLine("end");

    }

According to the code, it will create 1000 tasks per second. I watch the thread count in performance counter, the thread count increase slowly and smoothly, about 1 thread per second. And the memory also increase slowly and smoothly. when the thread count is 1028, it stoped increasing( I think the count is up to the max count of thread of thread pool, and the new task has to been queued.) btw, There's NO OutOfMemoryException.

But when I comment out 'Thread.Sleep(1);' Something strange happened.

In perfromance counter, the thread count growing up very quickly, and the total memory usage takes about 1445Mb. everything happens so fast. at last there's an OutOfMemoryException.

So what make this happen?

pinopino
  • 264
  • 2
  • 12
  • 1
    "According to the code, it will create 1000 tasks per second." Well, you're assuming that `Thread.Sleep(1)` *will* actually sleep for exactly 1 millisecond. I doubt that very much. – Jon Skeet Jun 24 '14 at 06:57
  • @JonSkeet my apologize for that statement. does it matters in this scenario? sorry i`m new to the Task and the thread pool stuff – pinopino Jun 24 '14 at 07:36
  • Well it matters in that you may well inky be creating 100 tasks per second, which is significantly less, and may well be enough for the system to handle. Basically the tight loop version is adding tasks faster than the system can reasonably be expected to deal with them. – Jon Skeet Jun 24 '14 at 07:45
  • I'm sure I read somewhere once that there was a rate limit on how quickly tasks are taken from the queue and dispatched. I can't seem to find any reference to it now though, maybe I'm making it up. – Patrick Allwood Jun 24 '14 at 07:46
  • @JonSkeet sorry, i still don`t get quite clearly. for the tight loop version, the pending task is getting more and more, and they are sure with some memory pay, so the memory usage getting more and more, am i right? – pinopino Jun 24 '14 at 08:06
  • @patchandthat hi, i think it`s the 'CLR via C#' - chapter 23 :) – pinopino Jun 24 '14 at 08:07
  • Yes, in the tight loop version you're queuing up tasks incredibly quickly - it's a bit like a more complicated version of `List x = new List(); while (true) { x.Add(new string('x', 10)); }` - it shouldn't be expected to work for long. – Jon Skeet Jun 24 '14 at 08:15

0 Answers0