# 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.&#x20;

This is made possible by a <mark style="color:blue;">**`ThreadCondition`**</mark>:&#x20;

```csharp
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 <mark style="color:blue;">**`parentToken`**</mark> is cancelled.
2. The first callback supplies a <mark style="color:blue;">**`childToken`**</mark> to be used in any method that returns a Task.&#x20;
   * This could be your own Task or "async" method.
3. The second callback should return <mark style="color:blue;">**`TRUE`**</mark> if the method should be running, or start for the first time.&#x20;
   * If it returns <mark style="color:blue;">**`FALSE`**</mark>, the condition will cancel the <mark style="color:blue;">**`childToken`**</mark> and await the <mark style="color:blue;">**`Task`**</mark> from the first callback.
4. The final parameter you can supply is how often this check occurs.&#x20;

{% hint style="info" %}
You may also use [Behavior Tree's](/core-modules/utility-classes/behavior-trees.md) in the condition callback. This will process the tree on every run.

```csharp
() => BehaviorTree.NewSequence("Conditionals", LeafNodes.NetworkAvailable)
```

{% endhint %}

#### 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.

```log
//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 starting
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.perigee.software/core-modules/utility-classes/thread-conditions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
