private void OnThreadStarted(object sender, EventArgs e) { var threads = DoGetThreads().Threads; var previousThreads = State.GetThreads(); var newThreads = threads.Except(previousThreads).ToArray(); foreach (var thread in newThreads) ThreadStarted?.Invoke(this, thread.Id); }
///<summary> /// Messaging system that runs tasks on the logic thread. ///</summary> private void TaskDoer() { ThreadStarted?.Invoke(this, null); TimerCallback watchDogCallBack = new TimerCallback(WatchDogElapsed); if (!(WatchDogTimerInterval is null)) { threadWatchDog = new Timer(watchDogCallBack, null, 0, Convert.ToInt32(WatchDogTimerInterval.Value.TotalMilliseconds)); } while (!CTStopRequested.IsCancellationRequested) { try { if (_taskCollection.IsCompleted) { Waiting = true; _logger()?.Debug("Waiting for next action"); } Action currentAction = _taskCollection.Take(); //** This is Thread Blocking Waiting = false; currentAction.Invoke(); _logger()?.Verbose("General Invoke Done"); if (_taskCollection.Count > 2) { _logger()?.Warning("Task Queue count has exceeded 2. The count is now at {count}", _taskCollection.Count); } } catch (Exception ex) { if (UnhandledException != null) { _logger()?.Error(ex, "Unhandled Exception Last Chance Catch. {NewLine} {Message}", Environment.NewLine, ex.Message); if (ex.StackTrace is null) { _logger()?.Error("Stack Trace was null"); } UnhandledException(this, new UnhandledExceptionEventArgs(ex, false)); } else { throw; } } } _logger()?.Debug("Thread loop has been closed"); threadWatchDog.Change(Timeout.Infinite, Timeout.Infinite); _logger()?.Debug("Watch dog timer stop requested."); //** trigger ThreadClosed Event ThreadFinished?.Invoke(this, null); }
protected virtual void OnThreadStarted(DebuggeeThreadEventArgs e) { ThreadStarted?.Invoke(this, e); }
public void StartReading() { IntPtr PtrToPreparsedData = IntPtr.Zero; try { // close the device (OK to call if it's already closed) StopReading(); lock (syncRoot) { // (Re)Open the device HidHandle = NativeMethods.CreateFile( devicepath, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, // No sharing IntPtr.Zero, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_FLAG_OVERLAPPED, IntPtr.Zero); int LastErr = Marshal.GetLastWin32Error(); if (HidHandle.IsInvalid) { Logger.Error(devicename, "Error opening path: " + devicepath); throw new Win32Exception(LastErr); } if (NativeMethods.HidD_GetPreparsedData(HidHandle, ref PtrToPreparsedData) == (byte)0) { Logger.Error(devicename, "Error reading HID preparsed data."); throw new PosControlException(rm.GetString("IDS_DEVICE_COMMUNICATION_FAILURE"), ErrorCode.Failure); } } NativeMethods.HIDP_CAPS DeviceCaps = new NativeMethods.HIDP_CAPS(); int retVal = NativeMethods.HidP_GetCaps(PtrToPreparsedData, ref DeviceCaps); if (retVal < 0) { Logger.Error(devicename, "Error reading HID capabilities: " + retVal.ToString(CultureInfo.InvariantCulture)); throw new PosControlException(rm.GetString("IDS_DEVICE_COMMUNICATION_FAILURE"), ErrorCode.Failure); } InputReportByteLength = DeviceCaps.InputReportByteLength; FeatureReportByteLength = DeviceCaps.FeatureReportByteLength; Logger.Info(devicename, "InputReportByteLength = " + InputReportByteLength.ToString(CultureInfo.InvariantCulture)); Logger.Info(devicename, "FeatureReportByteLength = " + FeatureReportByteLength.ToString(CultureInfo.InvariantCulture)); // Reset events ThreadTerminating.Reset(); ThreadStarted.Reset(); // start thread for getting input ReadThread = new Thread(new ThreadStart(ThreadMethod)); ReadThread.Name = "HidThread: " + devicename; ReadThread.IsBackground = true; ReadThread.Start(); // If the thread doesn't start in 30 seconds throw an exception if (!ThreadStarted.WaitOne(30000, false)) { Logger.Error(devicename, "HidThread - thread failed to start in 30 seconds."); throw new PosControlException(rm.GetString("IDS_THREAD_FAILED_TO_START"), ErrorCode.Failure); } Logger.Info(devicename, "HidThread - thread started successfully."); } catch (Exception e) { Logger.Error(devicename, "An exception occurred while attempting to open the device.", e); StopReading(); throw; } finally { // Free Preparsed Data if (PtrToPreparsedData != IntPtr.Zero) { NativeMethods.HidD_FreePreparsedData(PtrToPreparsedData); } } }
public void ThreadMethod() { threadId = Thread.CurrentThread.ManagedThreadId; try { // Signal the openning thread that we're up and running. if (ThreadStarted != null) { ThreadStarted.Set(); } using (FileStream fs = new FileStream(HidHandle, FileAccess.Read, InputReportByteLength, true)) { byte[] buffer = new byte[InputReportByteLength]; while (true) { IAsyncResult res = fs.BeginRead(buffer, 0, InputReportByteLength, AsyncCallback, null); // We need to wait for either IO to complete or the read to be signaled WaitHandle[] IOCompleteOrThreadTerminating = { res.AsyncWaitHandle, ThreadTerminating }; // Wait for data or thread termination if (1 == WaitHandle.WaitAny(IOCompleteOrThreadTerminating)) { break; } // Call endRead to get the # of bytes actually read. This will throw an exception // if the read was not successfull (i.e. the device was removed, etc). int bytesRead = fs.EndRead(res); Logger.Info(devicename, "read " + bytesRead.ToString(CultureInfo.InvariantCulture) + " bytes from device."); // Make sure we got the correct # of bytes if (bytesRead == InputReportByteLength) { // Get strong ref to callback delegate DataReadCallback callback = wdcallback.Target as DataReadCallback; if (callback == null) { break; } // report data to caller callback(buffer); callback = null; } else { // Unexpected data size - we'll thrown an exception for now. // This may need to change for devices that report variable length data. throw new PosControlException(rm.GetString("IDS_UNEXPECTED_NUMBER_BYTES"), ErrorCode.Failure); } } } } catch (Exception e) { // We must eat this exception and marshal it back to the calling thread or else the // CLR will terminate the process Logger.Error(devicename, "Exception occurred in HID read thread.", e); //if (e.Message.CompareTo("The device is not connected.\r\n") == 0) if (e is IOException) { lock (syncRoot) { if (null != HidHandle) { if (!HidHandle.IsClosed) { HidHandle.Close(); } HidHandle.Dispose(); HidHandle = null; } } } ThreadExceptionCallback excallback = wdexcallback.Target as ThreadExceptionCallback; if (excallback != null) { excallback(e); // report exception to caller } excallback = null; } }
/// <summary> /// 通知工作线程已启动。 /// </summary> /// <param name="e"></param> protected virtual void OnTaskThreadStarted(TaskThreadStartedEventArgs e) { ThreadStarted?.Invoke(this, e); }
/// <summary> /// 通知工作线程已启动。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void OnThreadStarted(object sender, TaskThreadStartedEventArgs e) { ThreadStarted?.Invoke(sender, e); }
public int CreateThread(ulong Handle, ulong DataOffset, ulong StartOffset) { ThreadStarted?.Invoke(this, null); return(HResult.Ok); }
private void Setup() { _processed = 0; ThreadStarted?.Invoke(this, null); }