5

I'm trying to reduce the memory usage of a console application I have. It is supposed to run for hours on end, but it seems like the memory usage is gradually increasing with each second. It does use multiple threads, and does a variety of things, but I read somewhere that having a lot of calls to Console.WriteLine can also cause memory spikes.

Because the application is constantly writing to the console, I thought that maybe the memory usage is because of this. Unfortunately, I can't easily clear the console because I'm redirecting the output to a monitoring window. I've turned it off temporarily, but the memory is still increasing, which tells me there's other things I need to address.

Before I go about hunting down memory leaks, I was wondering if anyone can confirm/verify whether having thousands of Console.WriteLine's could cause a memory leak, or if that's already handled appropriately by the redirected output buffer. I've tried to do a search, but haven't found much on this.

AlishahNovin
  • 1,904
  • 3
  • 20
  • 37
  • 1
    What makes you think that what you're seeing is a leak? Memory usage may well increase until there's enough pressure to warrant a collection; depending on your code and the environment it's running in, this could be a long time. How much memory is leaking per second, and what is the application doing? `Console.WriteLine` shouldn't consume any more memory than the message occupies in the buffer, unless there's something I've missed... – Dan Puzey Jul 24 '12 at 21:11
  • 1
    http://stackoverflow.com/questions/399847/net-memory-profiling-tools – spender Jul 24 '12 at 21:13

1 Answers1

5

Having thousands of calls to Console.WriteLine does not cause a memory leak. I have a long-running program (it's been up for 6 months now) that writes a few hundred lines per minute to the console, and its memory usage has remained level.

It's possible that writing thousands of lines infrequently all at once can cause memory spikes due to temporary strings, but those will be collected the next time GC is run. But a steady load of Console.WriteLine will just cause a steady memory load of uncollected strings. It won't be ever-increasing.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • 3
    Actually, that isn't always true. While Console.WriteLine is thread safe, if you do call it from multiple threads, you will get a handle leak where Events/Semaphores on other threads will not close. I have verified this in Win2003 .NET 4. I have not tried other platforms yet. – Brain2000 May 31 '13 at 00:04