Page 1 of 1

Non-Blocking Input Events

Posted: Wed Feb 01, 2023 7:05 pm
by scsm
I receive events as digital input from an IR device. I want to perform a bunch of things that will run async and take several seconds when the state of the input is true. During this time I will ignore all other state changes on this input.

Code: Select all

private async void DigitalInput_StateChange(object sender, Phidget22.Events.DigitalInputStateChangeEventArgs e)
{
   try
   {
      if (isInitialised)
      {
         await DigitalInputStatus((DigitalInput)sender, e.State);
      }
    }
   catch (PhidgetException ex)
   {
      Debug.WriteLine("[ERROR] StateChanged.PhEx " + ex.ErrorCode + " (" + ex.Description + "): " + ex.Detail);
   }
}
How can I make this non-blocking on the phidget? I want to immediately return and not "hold" onto the thread that called this event?

Is there any coding pattern or example for this scenario. i.e. running long running tasks from a phidget event?

Re: Non-Blocking Input Events

Posted: Thu Feb 02, 2023 12:26 pm
by Patrick
If you're interacting with a UI I'd use a BackgroundWorker, otherwise use a ThreadPool or Thread.

If you don't care about events at all until your task is finished, you can just deregister/register for the StateChange event at the start/end of your task.

-Patrick

Re: Non-Blocking Input Events

Posted: Tue Feb 07, 2023 7:24 pm
by scsm
We haven't tested it under load yet but it seems to work with a ThreadPool. Thanks for the suggestion.

Code: Select all

if (!scales.isWeighing)
{
    ThreadPool.QueueUserWorkItem(a => BeginWeighing(scales));
}