Page cover

Thread Conditions

Thread Conditional Wrap

There are times when you want to turn off or disable something running when a condition occurs. An example of this would be to only run a Coordinator when there is a known network connection available.

This is made possible by a ThreadCondition:

c.Add("OrderProcessing", (parentToken, l) =>
{
    ThreadCondition.Wrap(parentToken, 
        (childToken) => coordinator.StartAsync(childToken), 
        () => NetworkUtility.Available(), 
        TimeSpan.FromSeconds(5));
});

Let's take a look at what's happening:

  1. The method itself is thread blocking, so it won't return out until the parentToken is cancelled.

  2. The first callback supplies a childToken to be used in any method that returns a Task.

    • This could be your own Task or "async" method.

  3. The second callback should return TRUE if the method should be running, or start for the first time.

    • If it returns FALSE, the condition will cancel the childToken and await the Task from the first callback.

  4. The final parameter you can supply is how often this check occurs.

circle-info

You may also use Behavior Tree's in the condition callback. This will process the tree on every run.

Running the demo

In this example, flipping off the Wi-Fi radio of your development box will stop the coordinator from receiving new messages. Turning it back on will start the coordinator again.

Last updated