/// <summary> /// Tries to convert a given memory stream to the UTF16 encoding by adding an UTF16 BOM to the stream. /// </summary> /// <param name="stream">The stream to try to convert to.</param> /// <param name="encoding">The encoding successfully used with the stream data.</param> /// <param name="bigEndian"><c>true</c> to use the big endian byte order (most significant byte first); <c>false</c> to use the little endian byte order (least significant byte first).</param> /// <param name="noBom">A value indicating whether the detected unicode file contains a byte-order-mark.</param> /// <returns>A string converted into the UTF16 encoding if successful; otherwise null.</returns> public static string TryUtf16Encoding(MemoryStream stream, bool bigEndian, out Encoding encoding, out bool noBom) { noBom = false; if (!FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian && ByteMatch(GetEncodingComparisonBytes(stream), Utf16LittleEndianBom) || !FormSettings.Settings.SkipUnicodeDetectBe && bigEndian && ByteMatch(GetEncodingComparisonBytes(stream), Utf16BigEndianBom)) { try { encoding = new UnicodeEncoding(bigEndian, true, true); return(encoding.GetString(stream.ToArray())); } catch (Exception ex) { ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs { Exception = ex }); // failed.. encoding = null; return(null); } } // the user doesn't want this detection.. if (FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian || FormSettings.Settings.SkipUnicodeDetectBe && bigEndian) { // so just return.. encoding = null; return(null); } try // there is no BOM.. { // get the contents of the memory stream into a list of bytes.. List <byte> bytes = new List <byte>(stream.ToArray()); // insert the BOM.. // bytes.InsertRange(0, bigEndian ? Utf16BigEndianBom : Utf16LittleEndianBom); // try the UTF16 encoding with the BOM.. encoding = new UnicodeEncoding(bigEndian, false, true); noBom = true; return(encoding.GetString(bytes.ToArray())); } catch (Exception ex) { ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs { Exception = ex }); // failed.. encoding = null; return(null); } }
private void PacketReceivingThread() { try { while (_running) { var datapacket = new DataPacket(DefaultCodec); datapacket.ReadFromStream(_rawReadCodec, RemoteBoundTo, () => CompressThreshold, () => State); if (!PacketProvider.TryCreatePacket(datapacket.PacketId, datapacket.BoundTo, datapacket.State, out var packet) && ((packet = OnUnknownPacketReceived(datapacket)) is DataPacket || packet is null)) { _logger.Warn($"Unknown packet 0x{datapacket.PacketId:X2}"); continue; } packet.ReadFromStream(datapacket.Content); if (!OnPacketReceived(packet)) { continue; } lock (_receivePacketQueue) { _receivePacketQueue.Enqueue(packet); if (_waitReceiveCount != 0) { Monitor.Pulse(_receivePacketQueue); } } } } catch (EndOfStreamException) { _receivePacketQueue.Enqueue(null); } catch (Exception ex) { _logger.Error(ex); ExceptionOccurred?.Invoke(this, ex); } finally { lock (_receivePacketQueue) { if (_waitReceiveCount != 0) { Monitor.PulseAll(_receivePacketQueue); } } _running = false; State = ProtocolState.Closed; } }
/// <summary> /// Begin a task reading data from the Fanuc Device /// </summary> public void WriteOut(string data, FanucSocketOptions options) { if (SafeToProceed()) { ns.Flush(); // Removes extra data that is stuck in the socket cancelSource = new CancellationTokenSource(); opCancelToken = cancelSource.Token; // Main read task operation = new Task( cancellationToken: cancelSource.Token, creationOptions: TaskCreationOptions.LongRunning, action: () => { this.WriteOut_Main(data, options); } ); // If sending completes fully, fire event and dispose operation.ContinueWith( continuationOptions: TaskContinuationOptions.ExecuteSynchronously, continuationAction: (t) => { if (t.IsCompleted && !t.IsCanceled) { if (SendOperationCompleted != null) { SendOperationCompleted.Invoke(this, null); } } else if (t.IsFaulted) { if (ExceptionOccurred != null) { ExceptionOccurred.Invoke(this, t.Exception); } } cancelSource.Dispose(); cancelSource = null; operation.Dispose(); operation = null; ChangeState(FanucSocketState.Idle); } ); operation.Start(); } else { throw new FanucException("Operation in progress!"); } }
public ThreadGun <T> FillingMagazine(int magazineCount) { if (_action == null) { return(this); } void Action() { if (ExceptionOccurred == null) { _action(); } else { try { _action(); } catch (Exception ex) { ExceptionOccurred?.Invoke(this, null, null, ex); } } if (_waitingPeriod != 0) { Thread.Sleep(_waitingPeriod); _waitingPeriod = 0; _waitingCompletedAction?.Invoke(); } try { _magazine.TryPop(out var action); action.Invoke(); } catch (NullReferenceException) { _completed = 1; } } for (var i = 0; i < magazineCount; i++) { _magazine.Push(Action); } return(this); }
/// <summary> /// Tries to convert a given memory stream to the UTF8 encoding by adding an UTF8 BOM to the stream. /// </summary> /// <param name="stream">The stream to try to convert to.</param> /// <param name="encoding">The encoding successfully used with the stream data.</param> /// <param name="noBom">A value indicating whether the detected unicode file contains a byte-order-mark.</param> /// <returns>A string converted into the UTF8 encoding if successful; otherwise null.</returns> public static string TryUtf8Encoding(MemoryStream stream, out Encoding encoding, out bool noBom) { noBom = false; if (ByteMatch(GetEncodingComparisonBytes(stream), Utf8Bom)) { try { encoding = new UTF8Encoding(true, true); return(encoding.GetString(stream.ToArray())); } catch (Exception ex) { ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs { Exception = ex }); // failed.. encoding = null; return(null); } } try // there is no BOM.. { // get the contents of the memory stream into a list of bytes.. List <byte> bytes = new List <byte>(stream.ToArray()); // insert the BOM.. bytes.InsertRange(0, Utf8Bom); // try the UTF8 encoding with the BOM.. encoding = new UTF8Encoding(false, true); noBom = true; return(encoding.GetString(bytes.ToArray())); } catch (Exception ex) { ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs { Exception = ex }); // failed.. encoding = null; return(null); } }
public ThreadGun <T> FillingMagazine(int magazineCount) { if (_action == null) { return(this); } void Action() { if (ExceptionOccurred == null) { _action(); } else { try { _action(); } catch (Exception ex) { ExceptionOccurred?.Invoke(this, null, null, ex); } } Wait(); try { _magazine.TryPop(out var action); action.Invoke(); } catch (NullReferenceException) { IsCompleted = true; } } for (var i = 0; i < magazineCount; i++) { _magazine.Push(Action); } return(this); }
public static void Shutdown(string message, Exception e) { if (hasShutdown) { // Shutdown already in progress return; } hasShutdown = true; Log.Exception(e, message); if (isDispatcherInitialized) { var dispatcher = GetApplicationDispatcher(); if (dispatcher.CheckAccess()) { ShowExceptionDialog(e); } else { dispatcher.Invoke(() => ShowExceptionDialog(e)); } } if (Debugger.IsAttached) { Debugger.Break(); } if (DateTime.Now - StartTime >= MinTimeBeforeAutoRestart) { ExceptionOccurred?.Invoke(null, EventArgs.Empty); } if (isDispatcherInitialized) { Application.Current.Shutdown(0); } else { throw new Exception($"Unhandled exception {message}", e); } }
public ThreadGun <T> FillingMagazine(Action <T> action, T input) { void Action() { if (ExceptionOccurred == null) { _actionT(input); } else { try { _actionT(input); } catch (Exception ex) { ExceptionOccurred?.Invoke(this, _inputs, input, ex); } } if (_waitingPeriod != 0) { Thread.Sleep(_waitingPeriod); _waitingPeriod = 0; _waitingCompletedAction?.Invoke(); } try { _magazine.TryPop(out var act); act.Invoke(); } catch (NullReferenceException) { _completed = 1; } } if (ExceptionOccurred == null) { _magazine.Push(Action); } return(this); }
private void ClientAcceptedCallback(IAsyncResult ar) { Task.Run(() => { try { using (var connectedClient = new IdentifiedClient(_listener.EndAcceptTcpClient(ar))) { _connectedClients.Add(connectedClient); using (var stream = connectedClient.TcpClient.GetStream()) { while (connectedClient.TcpClient.Connected) { var data = _dataProvider.ReceiveData(stream); try { var m = UnpackResponse(data, connectedClient); if (m != null) { M.SendAsync(m); } } catch (Exception e) { L.Error("Exception in TcpServer: " + e.Message); } } } } } catch (Exception e) { ExceptionOccurred?.Invoke(this, e); } }); Log("Client connected"); WaitForClient(); }
public async void Start() { if (_isRunning) { return; } _isRunning = true; while (_isRunning) { try { var typing = await _keyboard.FetchTextAsync(); if (typing.Enter) { _lastTyping = typing; Confirmed?.Invoke(this, new TypingTextEventArgs(typing)); } else { var isEqual = _lastTyping != null && _lastTyping.Text == typing.Text && _lastTyping.CaretStartIndex == typing.CaretStartIndex && _lastTyping.CaretEndIndex == typing.CaretEndIndex; _lastTyping = typing; if (!isEqual) { Typing?.Invoke(this, new TypingTextEventArgs(typing)); } } } catch (Exception ex) { ExceptionOccurred?.Invoke(this, new ExceptionEventArgs(ex)); } await Task.Delay(20); } }
/// <summary> /// Queues an invocation to the pool. /// </summary> /// <param name="invocation">Invocation to execute.</param> /// <exception cref="InvalidOperationException">Thrown when the pool size is 0.</exception> public void Enqueue(AsyncReferenceInvocation invocation) { // dispatch method used to wrap invocations // this allows us to observe cancellations, wait on the semaphore, and // generally control internal state before and after invocation execution. async Task DispatchImpl() { try { if (_CancellationTokenSource.IsCancellationRequested) { return; } await _Semaphore.WaitAsync(CancellationToken).ConfigureAwait(false); await invocation.Invoke(CancellationToken).ConfigureAwait(false); _Semaphore.Release(1); } catch (Exception exception) when(exception is not OperationCanceledException) { // invoke exception event to propagate swallowed errors ExceptionOccurred?.Invoke(this, exception); } } // ensure the pool size isn't being modified _ModifyPoolReset.Wait(CancellationToken); // ensure the pool is actually accepting invocations and dispatch if (Size == 0) { ThrowHelper.ThrowInvalidOperationException($"Pool is empty. Call {nameof(DefaultPoolSize)}() or {nameof(ModifyPoolSize)}()."); } else { Task.Factory.StartNew(DispatchImpl, CancellationToken); } }
protected async Task EvaluateRuleAndExecuteActionsAsync() { try { //_logger?.Here(ClassType, Description).Debug("Started"); var result = await PerformEvaluateRuleAsync(); var(RuleIsMet, HasRuleIsMetChanged, data) = result; var tasks = new List <Task>(); foreach (var ruleAction in ruleActions) { tasks.Add(ruleAction.ExecuteAsync(RuleIsMet, HasRuleIsMetChanged, data)); } await Task.WhenAll(tasks.ToArray()); } catch (Exception ex) { if (ExceptionOccurred is null) { if (!_ThrowOnExceptions) { _logger?.Here(ClassType, Description).Warning(ex, "Unknown Exception was thrown during evaluation. No Exception EventHandler is subscribed, Exception Was ignored."); } else { _logger?.Here(ClassType, Description).Error(ex, "Unknown Exception was thrown during evaluation. No Exception EventHandler is subscribed. Re-throwing"); throw; } } else { _logger?.Here(ClassType, Description).Debug("Invoking Exception event handler"); ExceptionOccurred.Invoke(this, new ExceptionOccurredEventArgs(ex)); } } }
public ThreadGun <T> FillingMagazine(Action <T> action, T input) { void Action() { if (ExceptionOccurred == null) { _actionT(input); } else { try { _actionT(input); } catch (Exception ex) { ExceptionOccurred?.Invoke(this, _inputs, input, ex); } } Wait(); try { _magazine.TryPop(out var act); act.Invoke(); } catch (NullReferenceException) { IsCompleted = true; } } if (ExceptionOccurred == null) { _magazine.Push(Action); } return(this); }
public void StartMonitoringLoop() { try { if (CToken.IsCancellationRequested) { CTokenSource = new CancellationTokenSource(); } using (SerialPort serial = new SerialPort(this.SerialPortName, this.SerialPortBaudrate)) { serial.Open(); StartAllWorkers(); while (!CToken.IsCancellationRequested) { string newLine = serial.ReadLine(); string message = ReadMessage(newLine); SPClass serialPortClassWhichMessageHasBeenSentTo = ReadPrefixAndChooseClass(newLine); SendMessageToWorker(serialPortClassWhichMessageHasBeenSentTo, message); Thread.Sleep(100); Helper.NLogger.Debug("\n\n"); } } } catch (Exception ex) { Helper.NLogger.Error($"\n{ex.Message} \n{ex.InnerException}\n{ex.StackTrace}\n"); ExceptionOccurred?.Invoke(this, new EventArgs()); } }
/// <summary> /// Updates the and render. /// </summary> public void UpdateAndRender() { if (CanRender()) { IsBusy = true; var t0 = TimeSpan.FromSeconds((double)Stopwatch.GetTimestamp() / Stopwatch.Frequency); RenderStatistics.FPSStatistics.Push((t0 - lastRenderTime).TotalMilliseconds); RenderStatistics.Camera = viewport.CameraCore; lastRenderTime = t0; UpdateRequested = false; ++updateCounter; renderContext.AutoUpdateOctree = RenderConfiguration.AutoUpdateOctree; renderContext.EnableBoundingFrustum = EnableRenderFrustum; if (RenderConfiguration.UpdatePerFrameData) { viewport.Update(t0); renderContext.TimeStamp = t0; renderContext.Camera = viewport.CameraCore; renderContext.WorldMatrix = viewport.WorldMatrix; renderContext.OITWeightPower = RenderConfiguration.OITWeightPower; renderContext.OITWeightDepthSlope = RenderConfiguration.OITWeightDepthSlope; renderContext.OITWeightMode = RenderConfiguration.OITWeightMode; } PreRender(); UpdateSceneGraphRequested = false; try { if (renderBuffer.BeginDraw()) { OnRender(t0); renderBuffer.EndDraw(); } if (RenderConfiguration.RenderD2D && D2DTarget.D2DTarget != null) { OnRender2D(t0); } renderBuffer.Present(); } catch (SharpDXException ex) { var desc = ResultDescriptor.Find(ex.ResultCode); if (desc == global::SharpDX.DXGI.ResultCode.DeviceRemoved || desc == global::SharpDX.DXGI.ResultCode.DeviceReset || desc == global::SharpDX.DXGI.ResultCode.DeviceHung || desc == global::SharpDX.Direct2D1.ResultCode.RecreateTarget || desc == global::SharpDX.DXGI.ResultCode.AccessLost) { Log(LogLevel.Warning, $"Device Lost, code = {desc.Code}"); RenderBuffer_OnDeviceLost(RenderBuffer, EventArgs.Empty); } else { Log(LogLevel.Error, ex); EndD3D(); ExceptionOccurred?.Invoke(this, new RelayExceptionEventArgs(ex)); } } catch (Exception ex) { Log(LogLevel.Error, ex); EndD3D(); ExceptionOccurred?.Invoke(this, new RelayExceptionEventArgs(ex)); } finally { PostRender(); IsBusy = false; } lastRenderingDuration = TimeSpan.FromSeconds((double)Stopwatch.GetTimestamp() / Stopwatch.Frequency) - t0; RenderStatistics.LatencyStatistics.Push(lastRenderingDuration.TotalMilliseconds); OnRendered?.Invoke(this, EventArgs.Empty); } }
/// <summary> /// Process the received data from a <see cref="DtpFactory" /> /// </summary> /// <param name="data">The data which was given using the <see cref="DtpFactory.SendDataAction" /> delegate</param> /// <param name="start">The start position of the byte array</param> /// <returns>Returns the response which must get processed in <see cref="DtpFactory.Receive" /></returns> public byte[] Receive(byte[] data, int start) { data = LZF.Decompress(data, start); var functionNameLength = BitConverter.ToInt32(data, 16); var functionName = Encoding.UTF8.GetString(data, 20, functionNameLength); if (!_procedures.ContainsKey(functionName) && !_functions.ContainsKey(functionName)) { ExceptionOccurred?.Invoke(this, new UnhandledExceptionEventArgs( new InvalidOperationException($"Method with name {functionName} not found"))); var errorResponse = new byte[16 + functionNameLength]; Array.Copy(DtpFactory.FunctionNotFoundExceptionGuid.ToByteArray(), errorResponse, 16); Array.Copy(data, 20, errorResponse, 16, functionNameLength); return(errorResponse); } var parameterCount = BitConverter.ToInt32(data, 20 + functionNameLength); var parameterLengths = new List <int>(); var parameters = new Dictionary <int, byte[]>(); for (int i = 0; i < parameterCount; i++) { parameterLengths.Add(BitConverter.ToInt32(data, 24 + functionNameLength + i * 4)); } var offset = 0; for (int i = 0; i < parameterCount; i++) { var parameterData = new byte[parameterLengths[i]]; Array.Copy(data, 24 + functionNameLength + parameterCount * 4 + offset, parameterData, 0, parameterData.Length); parameters.Add(i, parameterData); offset += parameterData.Length; } var dtpParameters = new DtpParameters(parameters); byte[] result = null; try { DtpProcedure procedure; if (_procedures.TryGetValue(functionName, out procedure)) { procedure.Invoke(dtpParameters); } else { DtpFunction function; if (_functions.TryGetValue(functionName, out function)) { var returnedObject = function.Invoke(dtpParameters); if (returnedObject != null) { var typeList = new List <Type> { returnedObject.GetType() }; Type[] specialTypes; if (_specialTypes.TryGetValue(functionName, out specialTypes)) { typeList.AddRange(specialTypes); } result = new Serializer(typeList).Serialize(returnedObject); } } } } catch (Exception ex) { var exception = new DtpException { Message = ex.Message, StackTrace = ex.StackTrace, FunctionName = functionName, ParameterInformation = string.Join(", ", parameters.Select(x => x.Key + " - " + x.Value.Length + " B").ToArray()), SessionGuid = new Guid(data.Take(16).ToArray()) }; var exceptionData = new Serializer(typeof(DtpException)).Serialize(exception); var errorResponse = new byte[16 + exceptionData.Length]; Array.Copy(DtpFactory.ExceptionGuid.ToByteArray(), errorResponse, 16); Array.Copy(exceptionData, 0, errorResponse, 16, exceptionData.Length); ExceptionOccurred?.Invoke(this, new UnhandledExceptionEventArgs(ex)); return(LZF.Compress(errorResponse, 0)); } var response = new byte[16 + 4 + (result?.Length ?? 0)]; //Protocol //HEAD - 16 Bytes - Guid //HEAD - 4 Bytes - Response Length //DATA - result.Length - Result Length Array.Copy(data, 0, response, 0, 16); //copy guid Array.Copy(BitConverter.GetBytes(result?.Length ?? 0), 0, response, 16, 4); if (result != null) { Array.Copy(result, 0, response, 20, result.Length); } return(LZF.Compress(response, 0)); }
protected virtual void OnExceptionOccurred(DebuggeeExceptionEventArgs e) { ExceptionOccurred?.Invoke(this, e); }
private void OnExceptionOccurred(Exception value) { ExceptionOccurred?.Invoke(this, value); }
/// <summary> /// Tries different unicode encodings for a given file (with or without a BOM). /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="encoding">The detected encoding if any.</param> /// <param name="bigEndian">A value indicating whether the detected encoding is big-endian.</param> /// <param name="noBom">A value indicating whether the detected unicode file contains a byte-order-mark.</param> /// <returns>The contents of the file as a string if an unicode encoding variant was found for it.</returns> public static string TryEncodings(string fileName, out Encoding encoding, out bool bigEndian, out bool noBom) { noBom = false; bigEndian = false; try { using FileStream fileStream = File.OpenRead(fileName); using MemoryStream memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); // try the UTF8 encoding.. var result = TryUtf8Encoding(memoryStream, out encoding, out noBom); if (result != null) { bigEndian = false; return(result); } // try the UTF16 encoding with LittleEndian.. result = TryUtf16Encoding(memoryStream, false, out encoding, out noBom); if (result != null) { bigEndian = false; return(result); } // try the UTF16 encoding with BigEndian.. result = TryUtf16Encoding(memoryStream, true, out encoding, out noBom); if (result != null) { bigEndian = true; return(result); } // try the UTF32 encoding with LittleEndian.. result = TryUtf32Encoding(memoryStream, false, out encoding, out noBom); if (result != null) { bigEndian = false; return(result); } // try the UTF32 encoding with BigEndian.. result = TryUtf32Encoding(memoryStream, true, out encoding, out noBom); if (result != null) { bigEndian = true; return(result); } } catch (Exception ex) { ExceptionOccurred?.Invoke("TryEncodings", new EncodingExceptionEventArgs { Exception = ex }); // failed.. encoding = null; return(null); } return(null); }
public ThreadGun <T> FillingMagazine() { _magazine = new ConcurrentStack <Action>(); if (_actionT != null) { foreach (var input in _inputs) { void Action() { if (ExceptionOccurred == null) { _actionT(input); } else { try { _actionT(input); } catch (Exception ex) { ExceptionOccurred?.Invoke(this, _inputs, input, ex); } } if (_waitingPeriod != 0) { Thread.Sleep(_waitingPeriod); _waitingPeriod = 0; _waitingCompletedAction?.Invoke(); } try { _magazine.TryPop(out var action); action.Invoke(); } catch (NullReferenceException) { _completed = 1; } } _magazine.Push(Action); } } else if (_action != null) { void Action() { if (ExceptionOccurred == null) { _action(); } else { try { _action(); } catch (Exception ex) { ExceptionOccurred?.Invoke(this, null, null, ex); } } if (_waitingPeriod != 0) { Thread.Sleep(_waitingPeriod); _waitingPeriod = 0; _waitingCompletedAction?.Invoke(); } try { _magazine.TryPop(out var action); action.Invoke(); } catch (NullReferenceException) { _completed = 1; } } for (var i = 0; i < _magazineCount; i++) { _magazine.Push(Action); } } else if (_func != null) { foreach (var input in _inputs) { async void AsyncAction() { var task = Task.Run(async() => await _func(input)); AddActiveTask(task); if (ExceptionOccurred == null) { await task; } else { try { await task; } catch (Exception ex) { ExceptionOccurred?.Invoke(this, _inputs, input, ex); } } if (_waitingPeriod != 0) { Thread.Sleep(_waitingPeriod); _waitingPeriod = 0; _waitingCompletedAction?.Invoke(); } try { _magazine.TryPop(out var action); action.Invoke(); } catch (NullReferenceException) { _completed = 1; } } _magazine.Push(AsyncAction); } } return(this); }
public void OnExceptionOccurred(Exception ex) => ExceptionOccurred?.Invoke(ex.Message);
private void OnExceptionOccurred(Exception value) { ExceptionOccurred?.Invoke(this, value, PushToThreadPool); }
protected void OnExceptionOccurred(Exception ex) { Debug.Fail("exception occurred while executing sql statements", ex.Message); ExceptionOccurred?.Invoke(this, ex); }
private void OnExceptionOccurred(Exception exception) { ExceptionOccurred?.Invoke(this, new ExceptionEventArgs(exception)); }
private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs args) { ExceptionOccurred?.Invoke(args); return(Task.CompletedTask); }
/// <summary> /// /// </summary> /// <param name="value"></param> protected void OnExceptionOccurred(Exception value) { ExceptionOccurred?.Invoke(this, value); }
private void OnExceptionOccurred(Exception exception) { ExceptionOccurred?.Invoke(this, exception); }
public ThreadGun <T> FillingMagazine(T input) { if (_action != null) { throw new Exception("This action doesn't have input"); } if (_actionT != null) { void Action() { if (ExceptionOccurred == null) { _actionT(input); } else { try { _actionT(input); } catch (Exception ex) { ExceptionOccurred?.Invoke(this, _inputs, input, ex); } } if (_waitingPeriod != 0) { Thread.Sleep(_waitingPeriod); _waitingPeriod = 0; _waitingCompletedAction?.Invoke(); } try { _magazine.TryPop(out var action); action.Invoke(); } catch (NullReferenceException) { _completed = 1; } } _magazine.Push(Action); } else if (_func != null) { async void AsyncAction() { var task = Task.Run(async() => await _func(input)); AddActiveTask(task); if (ExceptionOccurred == null) { await task; } else { try { await task; } catch (Exception ex) { ExceptionOccurred?.Invoke(this, _inputs, input, ex); } } if (_waitingPeriod != 0) { Thread.Sleep(_waitingPeriod); _waitingPeriod = 0; _waitingCompletedAction?.Invoke(); } try { _magazine.TryPop(out var action); action.Invoke(); } catch (NullReferenceException) { _completed = 1; } } _magazine.Push(AsyncAction); } return(this); }
private void OnExceptionOccurred(Exception exception) { ExceptionOccurred?.Invoke(this, new ConnectionExceptionEventArgs <T>(this, exception)); }
/// <summary> /// Invokes the ExceptionOccurred event. /// </summary> protected virtual void OnExceptionOccured() { ExceptionOccurred?.Invoke(this, EventArgs.Empty); }