Skip to content

Commit

Permalink
Now closes unused serial devices that are not nF devices (#114)
Browse files Browse the repository at this point in the history
  • Loading branch information
josesimoes authored Feb 5, 2018
1 parent d2cc3c8 commit db6d38c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,20 @@ private void CloseCurrentlyConnectedDevice()

Debug.WriteLine($"Closing device {_deviceInformation?.Id}");

var tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(() => _device.Dispose()));
// dispose on a Task to give it a timeout to perform the Dispose()
// this is required to be able to actually close devices that get stuck with pending tasks on the in/output streams
var closeTask = Task.Factory.StartNew(() =>
{
// This closes the handle to the device
_device.Dispose();
});

// This closes the handle to the device
Task.WaitAll(tasks.ToArray(), 2000);
// need to wrap this in try-catch to catch possible AggregateExceptions
try
{
Task.WaitAll(new Task[] { closeTask }, TimeSpan.FromMilliseconds(1000));
}
catch { }

_device = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,13 @@ private async void AddDeviceToList(DeviceInformation deviceInformation, String d
else
{
Debug.WriteLine("Invalid serial device: " + deviceInformation.Id);
newNanoFrameworkDevice.Disconnect();
}
}
else
{
Debug.WriteLine("Couldn't connect to serial device: " + deviceInformation.Id);
newNanoFrameworkDevice.Disconnect();
}

// clear tentative list
Expand Down Expand Up @@ -414,11 +416,16 @@ private async void OnDeviceEnumerationCompleteAsync(DeviceWatcher sender, object

NanoFrameworkDevices.Add(device);
}
else
{
((NanoDevice<NanoSerialDevice>)device).Disconnect();
}
}
else
{
// couldn't open device
Debug.WriteLine($"Checking device: {(((NanoDevice<NanoSerialDevice>)device).Device.DeviceInformation.DeviceInformation.Id)} FAILED");
((NanoDevice<NanoSerialDevice>)device).Disconnect();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -645,11 +645,12 @@ public void StopProcessing()
{
_backgroundProcessorCancellation.Cancel();

// need to wrap this in try-catch to catch possible AggregateExceptions
try
{
Task.WaitAll(_backgroundProcessor);
}
catch (AggregateException) { }
catch { }

_backgroundProcessor = null;
}
Expand Down

0 comments on commit db6d38c

Please sign in to comment.