Repository navigation
Description
Summary
WaveOutEvent.Stop() / Dispose() do not wait for the playback thread. A buffer can be queued again after waveOutReset, and WaveOutBuffer.Dispose then releases its memory while the driver still owns it. The process dies with an access violation (0xC0000005) on a driver thread, or later with unrelated-looking errors (ExecutionEngineException / Internal CLR error 0x80131506, AccessViolationException in code that has nothing to do with audio).
PR #1502 stops the crash on main (the buffer is leaked when waveOutUnprepareHeader returns WaveStillPlaying). Two things remain:
release/2.x(2.4.0) does not have that fix and still crashes.- The cause is still there: a buffer can be queued after the reset during an ordinary
Stop(), so the "still playing" path, described in Harden file parsers against malformed input #1502 as one that normal shutdown should not hit, can be hit.
Results
Windows 11, .NET 10.0.12, one machine and one audio driver, default output device.
| NAudio | slow (forced interleaving) |
fast (no artificial delay) |
|---|---|---|
| 2.2.1 | crashed 3 / 3 | crashed 4 / 5 runs |
| 2.4.0 | crashed 3 / 3 | crashed 1 / 4 runs |
| 3.3.0 | crashed (every run, see note below the program) | no crash in 4 runs |
| 3.4.0-preview.1 | no crash, 3 / 3 | not tested |
A fast run lasts up to about two minutes; the runs that did not crash were stopped after 1250–1750 cycles. With an in-memory silent source instead of a file, fast did not crash in about 2000 cycles per run (4 runs).
The faulting address in all the crashes we looked up in the Windows event log was inside memcpy in ucrtbase.dll. In a dump of a real crash (same address), the faulting thread was a wdmaud.drv thread copying from an address in a part of the managed heap that was no longer allocated.
Repro
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NAudio" Version="2.4.0" />
</ItemGroup>
</Project>using System.Diagnostics;
using NAudio.Wave;
// Usage: repro [slow|fast]
// slow: forces the interleaving (Stop while the playback thread is inside Read)
// fast: no artificial delay: a Windows sound file at volume zero, Dispose 0-5 ms after Play, with the CPU busy
var slow = args.Length == 0 || args[0] == "slow";
var random = new Random(1);
if (!slow)
for (var i = 0; i < Environment.ProcessorCount; i++)
new Thread(() => { while (true) { } }) { IsBackground = true }.Start();
for (var cycle = 1; cycle <= (slow ? 50 : 10000); cycle++)
{
var source = new Silence(60);
using var file = slow ? null : new AudioFileReader(@"C:\Windows\Media\Alarm01.wav") { Volume = 0 };
var output = new WaveOutEvent();
using var stopped = new ManualResetEventSlim();
output.PlaybackStopped += (_, _) => stopped.Set();
output.Init((IWaveProvider?)file ?? source);
output.Play();
if (slow)
{
source.Reading.Wait();
output.Stop(); // waveOutReset, while the playback thread is inside Read...
stopped.Wait(); // ...which then calls waveOutWrite, after the reset
}
else
{
var watch = Stopwatch.StartNew();
var microseconds = random.Next(0, 5000);
while (watch.Elapsed.TotalMicroseconds < microseconds) { }
}
output.Dispose();
// reuse the memory that has just been released
for (var k = 0; k < 600; k++) Array.Fill(new byte[random.Next(1000, 60000)], (byte)0xCD);
GC.Collect(2, GCCollectionMode.Aggressive, true, true);
if (slow) Thread.Sleep(100);
if (slow || cycle % 250 == 0) Console.WriteLine($"cycle {cycle} survived");
}
Console.WriteLine("completed without crashing");
sealed class Silence(int readDelayMilliseconds) : IWaveProvider
{
public ManualResetEventSlim Reading { get; } = new();
public WaveFormat WaveFormat { get; } = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);
public int Read(byte[] buffer, int offset, int count)
{
Reading.Set();
if (readDelayMilliseconds > 0) Thread.Sleep(readDelayMilliseconds);
Array.Clear(buffer, offset, count);
return count;
}
}Note for 3.x: replace new WaveOutEvent() with new WaveOut() and implement Read(Span<byte> buffer).
What happens (2.2.1 / 2.4.0 source)
DoPlaybackchecksplaybackState == Playing, then refills and queues buffers (OnDone→waveOutWrite).Stop()sets the state toStoppedand callswaveOutResetwhile the playback thread is between that check andwaveOutWrite.- The write succeeds after the reset: the buffer is in the queue again.
Dispose→Stop()does nothing the second time.WaveOutBuffer.Disposefrees theGCHandles of the data buffer and of the header before callingwaveOutUnprepareHeader, and ignores its result.- The driver keeps reading the data buffer (and writing the header flags) in memory the GC is now free to reuse or decommit.
Inspecting the header flags through reflection after Stop() and PlaybackStopped, WHDR_INQUEUE was still set in 40 of 40 iterations of the slow scenario, on 2.2.1, 2.4.0 and also on 3.4.0-preview.1 (InQueue there). So waiting for PlaybackStopped before Dispose, as suggested when #339 was closed, is not enough in this case.
On main, from reading the code (not measured): when the new path is taken, the buffer stays pinned, the header is leaked and waveOutClose would be called with a buffer still queued.
Possible fixes
- Have
Stop()(or at leastDispose()) join the playback thread, then callwaveOutResetagain before unpreparing the buffers. - Or make the state check and
waveOutWriteatomic with respect to the reset: checkplaybackStateinsidewaveOutLock, in the same lock thatStop()holds while it changes the state and callswaveOutReset. - For 2.x: at least backport the
WaveStillPlayinghandling of Harden file parsers against malformed input #1502, callingwaveOutUnprepareHeaderbefore freeing the handles.
We have not tried these changes in NAudio.
Related
- WaveOutEvent.Dispose() race condition #339 (same lack of synchronisation, reported as intermittent exceptions)
- WaveOutEvent causes crash in thread wdmaud.drv #416 (access violation in
wdmaud.drvwithWaveOutEvent; possibly the same cause, not verified) - Harden file parsers against malformed input #1502 (current mitigation on
main)
Workaround
We are moving to WasapiOut, whose Stop() joins its playback thread: a stress test with the same timing (stop 0-5 ms after play, CPU busy) ran without crashes.
Context
Found in a desktop app using NAudio 2.2.1, where it first showed up as random crashes of the test suite. Analysis and fix are tracked in giansalvo/GGCalendar#105 (written in Italian).
Activity
markheath commentedon Nov 26, 2026
Thanks for reporting. Any reason why you are not using NAudio 3? We are not actively developing on NAudio 2 at the moment
Stop WaveOutEvent queueing a buffer again after Stop() resets the dev…
markheath commentedon Nov 26, 2026
I've pushed fixes for this to v2 and v3 and I've made some improvements to the v2 release process so in due course we can more easily release versions of the 2.x branch. Some notes from Claude...
Let me know if this meets your needs and they can go live in the next full release of NAudio
giansalvo commentedon Nov 27, 2026
markheath commentedon Nov 27, 2026
OK, well hopefully 3.4.0 is out soon. Also WASPI is the recommended approach going forwards for audio playback in Windows as it replaced the old winmm APIs that WaveOut/WaveOutEvent usess as the preferred audio API in Windows 20 years ago! In NAudio 3 there is a new
WasapiPlayerclass that is designed to be easier to configure and exposes more capabilities, butWasapiOutis still there if you need it.Stop WaveOut queueing a buffer again after Stop() resets the device (n…