使用DryWetMidi处理MIDI事件时C#内存增长的解决方法咨询
The 15MB memory growth that stops after MIDI activity is most likely due to DryWetMidi's internal performance optimizations (like object pooling for MIDI events) or default logging, not a permanent leak. Here's how to minimize or eliminate this growth:
1. Disable DryWetMidi Logging
DryWetMidi enables logging by default, which can accumulate temporary memory for log messages when handling high volumes of MIDI events. Turn it off entirely to cut down on allocations:
using Melanchall.DryWetMidi.Common; using Melanchall.DryWetMidi.Core; using Melanchall.DryWetMidi.Devices; static async Task Main(string[] args) { // Disable logging before initializing the device LogManager.Default.SetLogLevel(LogLevel.Off); InputDevice nano = InputDevice.GetByName("nanoKONTROL2"); nano.StartEventsListening(); Console.WriteLine("start"); for (int i = 1; i < 101; i++) { await Task.Delay(1000); Console.WriteLine(i + " seconds passed"); } Console.WriteLine("end"); nano.StopEventsListening(); nano.Dispose(); }
2. Adjust Input Buffer Size
DryWetMidi uses internal buffers to handle incoming MIDI data. Reducing the buffer size can lower initial memory overhead. Use InputDeviceSettings to configure this:
var settings = new InputDeviceSettings { BufferSize = 256 // Smaller buffer size; adjust based on your needs }; InputDevice nano = InputDevice.Create("nanoKONTROL2", settings);
Note: A too-small buffer might cause dropped MIDI events if your controller sends data very rapidly, so test to find a balance between memory usage and reliability.
3. Verify Memory Release
Since the memory growth stops after activity, confirm that the memory is released once you dispose the device. Use a memory profiler (like Visual Studio's built-in profiler) to check if the allocated memory is reclaimed by the GC after calling Dispose(). If it is, the growth is just temporary pooling for performance, which is safe to leave as-is if memory usage is acceptable.
4. Avoid Unnecessary Event Retention
If you later add event handlers to the device, make sure you unsubscribe from them before disposing to prevent accidental memory leaks. For example:
// When adding a handler nano.EventReceived += OnMidiEventReceived; // Before disposing nano.EventReceived -= OnMidiEventReceived;
Even though your current code doesn't use event handlers, this is a good practice for future extensions.
内容的提问来源于stack exchange,提问作者CodeCrafter 1

