/// <summary> /// Does the task work. /// </summary> /// <param name="token">The token.</param> private void LidarTaskDoWork(CancellationToken token) { try { // Check if on start is canceled token.ThrowIfCancellationRequested(); IsRunning = true; while (true) { if (token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } Thread.Sleep(400); if (RpLidarInterface.LidarIsConnected() != 1) { return; } var scanResult = RpLidarInterface.GetCurrentVectors(); OnScanDataReceived?.Invoke(this, new LidarDataReceivedEventArgs(scanResult, ++_ScanNumber)); } } catch (OperationCanceledException) { throw; } catch (AggregateException e) { foreach (var v in e.InnerExceptions) { Console.WriteLine(v); } } catch (Exception ex) { Console.WriteLine(ex); } finally { // Stop device and dispose driver try { // Exception happens when closing an connection // where someone has reconnect USB cable during usage RpLidarInterface.LidarDisposeDriver(); } catch (Exception ex) { Console.WriteLine(ex); } IsRunning = false; } }
/// <summary> /// Stops this instance. /// </summary> /// <returns><c>true</c> if successfully, <c>false</c> otherwise.</returns> public bool LidarStop() { if (!IsRunning || IsDisposed) { return(false); } _TokenSource?.Cancel(); try { _Task?.Wait(_Token); } catch (OperationCanceledException) { } catch (AggregateException e) { foreach (var v in e.InnerExceptions) { Console.WriteLine(v); } } finally { _TokenSource?.Dispose(); } try { // Stop device and dispose driver RpLidarInterface.LidarDisposeDriver(); if (RpLidarInterface.LidarIsConnected() != 1) { return(true); } else { return(false); } } finally { if (RpLidarInterface.LidarIsConnected() != 1) { OnDeviceDisconnected?.Invoke(this, EventArgs.Empty); } } }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void LidarDispose(bool disposing) { if (!_Disposed) { if (!IsRunning) { return; } try { // Signal exit _TokenSource?.Cancel(); } catch { } try { // Wait until task is ended _Task.Wait(5000, _Token); } catch (OperationCanceledException) { // Task tell us it's ended } catch (AggregateException e) { foreach (var v in e.InnerExceptions) { Console.WriteLine(v); } } finally { // Dispose token source _TokenSource?.Dispose(); // Stop motor, disconnect device and dispose driver RpLidarInterface.LidarDisposeDriver(); _Disposed = true; } } }