简体   繁体   中英

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:

  • In VS under debugger - the memory usage is flat. No leaks.
  • Run the exe directly (outside of vs and not under debugger) - the memory keeps growing to gbs and eventually OOMs at around ~4gb.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM