# MLPredictorExtensions

This class contains extension methods for working with predictors.

## Async Predictions

```csharp
/// <summary>
/// Create an async predictor from a predictor.
/// This typically results in significant performance improvements,
/// as predictions are run on a worker thread.
/// </summary>
/// <param name="predictor">Backing predictor to create an async predictor with.</param>
/// <returns>Async predictor which runs predictions on a worker thread.</returns>
static MLAsyncPredictor<TOutput> ToAsync<TOutput> (this IMLPredictor<TOutput> predictor);
```

Some models might not be able to run in realtime. This doesn't mean they can't be used; in fact many models run slower-than-realtime in interactive applications. In this situation, it becomes beneficial to run predictions asynchronously. NatML provides the `MLAsyncPredictor` which is a wrapper around any existing predictor for this purpose:

```csharp
// Create a predictor
var predictor = new MobileNetv2Predictor(...);
// Then make it async!
var asyncPredictor = predictor.ToAsync();
```

The async predictor spins up a dedicated worker thread for making predictions, completely freeing up your app to perform other processing:

```csharp
// Before, we used to make predictions on the main thread:
var (label, confidence) = predictor.Predict(...);
// Now, we can make predictions on a dedicated worker thread:
var (label, confidence) = await asyncPredictor.Predict(...);
```

When making predictions in streaming applications (like in camera apps), you can check if the async predictor is ready to make more predictions, so as not to backup the processing queue:

```csharp
// If the predictor is ready, queue more work
if (asyncPredictor.readyForPrediction)
    var output = await asyncPredictor.Predict(...);
```

Finally, you must `Dispose` the predictor when you are done with it, so as not to leave threads and other resources dangling.

{% hint style="danger" %}
Do not use predictors from multiple threads. So once you create an [`MLAsyncPredictor`](broken://pages/-MZnQIsGHofi0magWYLW) from an inner predictor, do not use the inner predictor.
{% endhint %}


---

# 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.natml.ai/unity/api/mlpredictorextensions.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.
