首页 > 解决方案 > Memory leak on unawaited tasks which throw exception?

问题描述

Below is a simple console app code, which repeatedly fires an async call but doesn't await. The called function throws an exception. Running this console app produces following results:

I am not sure how to explain these results. Any help would be much appreciated.

    static void Main(string[] args)
    {
        while (true)
        {
            Task.Run(() => RunMain());
        }
        Console.ReadLine();
    }
    static Exception ex = new Exception();
    private static void RunMain()
    {
        throw ex;
    }

edit: I am primarily interested in why the memory leaks when unobserved exceptions are thrown continuously.

标签: c#.nettask-parallel-libraryclr

解决方案


When you constantly create new tasks with that Task.Run(), you’re creating new objects that are taking up more memory. I believe what you’re overlooking is the fact that the Task itself is an object.

When you call Task.Run(), you add a Task to the queue of the Threadpool. I would bet that the memory leak is from new tasks continually being added to the Threadpool’s queue and the threadpool not being able to keep up with it.


推荐阅读