melanchall / drywetmidi

.NET library to read, write, process MIDI files and to work with MIDI devices
https://melanchall.github.io/drywetmidi
MIT License
540 stars 75 forks source link

Device is already in use (IN_OPENRESULT_ALLOCATED) #205

Closed thebitbrine closed 2 years ago

thebitbrine commented 2 years ago

I opened the MIDI device using the following code:

IInputDevice _inputDevice = InputDevice.GetByName(deviceName);
_inputDevice.EventReceived += OnEventReceived;
_inputDevice.StartEventsListening();

Since there's no way to disconnect the device, I tried the following:

_inputDevice.StopEventsListening();
_inputDevice = null;

After switching to another MIDI input, now I want to connect to the first one but this is what I get: Device is already in use (IN_OPENRESULT_ALLOCATED)

How can I Dispose/Disconnect the first device so I can connect to it later?

thebitbrine commented 2 years ago

I was using IInputDevice instead of InputDevice, consuming the class directly exposes .Dispose() which solves the problem.

Final code:

//Init
IInputDevice _inputDevice = InputDevice.GetByName(deviceName);
_inputDevice.EventReceived += OnEventReceived;
_inputDevice.StartEventsListening();

//Dispose
_inputDevice.StopEventsListening();
_inputDevice.Dispose();
melanchall commented 2 years ago

@thebitbrine Hmm, maybe it's a good idea to derive IInputDevice from IDisposable. I'll think about it.

melanchall commented 2 years ago

Well, now IInputDevice and IOutputDevice are derived from IDisposable. Changes are available in a prerelease version of the DryWetMIDI on NuGet – 6.1.2-prerelease3.

melanchall commented 2 years ago

:rocket: 6.1.2 version is released now!

Prerelease NuGet packages will be unlisted soon, so please update the package references to the new version.

Thanks for using the library!