From 6728f6413db611abf416510287dc86bfce062867 Mon Sep 17 00:00:00 2001 From: Roman Lumetsberger Date: Fri, 18 Aug 2017 16:04:51 +0200 Subject: [PATCH] fix https://github.com/DarthAffe/OBD.NET/issues/3 --- .../OBD.NET.Common/Devices/SerialDevice.cs | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/OBD.NET/OBD.NET.Common/Devices/SerialDevice.cs b/OBD.NET/OBD.NET.Common/Devices/SerialDevice.cs index d9c8dcc..7427e0b 100644 --- a/OBD.NET/OBD.NET.Common/Devices/SerialDevice.cs +++ b/OBD.NET/OBD.NET.Common/Devices/SerialDevice.cs @@ -222,22 +222,27 @@ namespace OBD.NET.Devices while (!commandCancellationToken.IsCancellationRequested) { currentCommand = null; - if(commandQueue.TryTake(out currentCommand, Timeout.Infinite, commandCancellationToken.Token)) + try { - Logger?.WriteLine("Writing Command: '" + currentCommand.CommandText.Replace('\r', '\'') + "'", OBDLogLevel.Verbose); - - if (Connection.IsAsync) + if (commandQueue.TryTake(out currentCommand, Timeout.Infinite, commandCancellationToken.Token)) { - await Connection.WriteAsync(Encoding.ASCII.GetBytes(currentCommand.CommandText)); - } - else - { - Connection.Write(Encoding.ASCII.GetBytes(currentCommand.CommandText)); + Logger?.WriteLine("Writing Command: '" + currentCommand.CommandText.Replace('\r', '\'') + "'", OBDLogLevel.Verbose); + if (Connection.IsAsync) + { + await Connection.WriteAsync(Encoding.ASCII.GetBytes(currentCommand.CommandText)); + } + else + { + Connection.Write(Encoding.ASCII.GetBytes(currentCommand.CommandText)); + + } + //wait for command to finish + commandFinishedEvent.WaitOne(); } - //wait for command to finish - commandFinishedEvent.WaitOne(); } + catch (OperationCanceledException) + {/*ignore, because it is thrown when the cancellation token is canceled*/} } } @@ -246,6 +251,7 @@ namespace OBD.NET.Devices /// public virtual void Dispose() { + commandQueue.CompleteAdding(); commandCancellationToken?.Cancel(); commandWorkerTask?.Wait(); Connection?.Dispose();