naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.58k stars 1.1k forks source link

NAudio > Memory Leak #138

Closed qzzf1w closed 7 years ago

qzzf1w commented 8 years ago

MMDevice has a property of type AudioEndpointVolume AudioEndpointVolume is dispossable. MMDevice is not.

markheath commented 8 years ago

are you sure there is actually a memory leak possible? Have you got a repro?

The big challenge in WASAPI interop is mixing the world of .NET objects which are garbage collected if nothing references them any more, and COM objects which use reference counting. I initially put disposables on everything, to allow you to deterministically free up COM objects. But I found it caused no end of crashes with shared objects getting freed while other things were still actually requiring them. The whole thing needs revisiting in the future, but simply cascading Disposable calls down causes more problems than it solves.

qzzf1w commented 8 years ago

Yes, we are encountering a memory leak with Naudio. We are newing a MMDevice every 30 seconds or so. DotMemory says we are leaking. If we call microphoneDevice.AudioEndpointVolume.Dispose() before the microphoneDevice goes out of scope, the leak appears to go away.

BTW I note that AudioClient is also disposable. To make matters worse a new instance is newed up every time the AudioClient property is called on MMDevice. WHich was a bit confusing until I looked at the source.

I agree the mix of Com and .net can be tricky.

markheath commented 8 years ago

I see, creating lots of MMDevices would cause this problem. As I said, the whole area probably needs revisiting, but if you have a fix that you are able to thoroughly test then feel free to submit a PR

nleclerc commented 7 years ago

That leak is still present. I'm making an app that regularly checks the status of audio devices and memory usage keeps on growing. The app literally only lists audio devices periodically so there's no chance it's some other part of the code.