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:
The method itself is thread blocking, so it won't return out until the
parentTokenis cancelled.The first callback supplies a
childTokento be used in any method that returns a Task.This could be your own Task or "async" method.
The second callback should return
TRUEif the method should be running, or start for the first time.If it returns
FALSE, the condition will cancel thechildTokenand await theTaskfrom the first callback.
The final parameter you can supply is how often this check occurs.
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.
//Off
[11:43:11 INF](OrderProcess) Coordinator OrderProcess cancellation requested
[11:43:11 INF](OrderProcess) Coordinator OrderProcess cancellation complete
//Back on
[11:43:16 INF](OrderProcess) Coordinator OrderProcess startingLast updated

