Artificial intelligence is becoming an important part of modern desktop applications. Developers are adding features such as document classification, image recognition, text analysis, object detection, and intelligent recommendations to applications that traditionally relied on cloud-based services.
However, sending every request to a cloud AI service is not always the best option. Some applications need to process sensitive information locally, work without an internet connection, or reduce the cost and latency associated with remote API calls.
Windows ML provides a way to run machine learning models directly on Windows devices. A C# application can load a supported model, provide input data, execute inference, and consume the results without sending the data to an external AI service.
Windows ML is designed to simplify local model execution by managing the inference environment and selecting suitable execution providers. Depending on the device and available hardware, inference can use supported CPU, GPU, or NPU acceleration.
For .NET developers, this creates an opportunity to add local AI capabilities to existing Windows applications without building a separate inference service.
In this article, we will explore Windows ML, understand its architecture, prepare a C# project, load an ONNX model, run inference, and handle common issues when integrating local AI into a Windows desktop application.
Understanding Windows ML
Windows ML is Microsoft's machine learning inference platform for Windows applications.
It allows developers to execute trained machine learning models locally on Windows devices. Instead of implementing the model's algorithms manually, developers load a model that has already been trained and use it to make predictions.
For example, an application might use a trained image classification model to identify objects in a photograph.
The application provides an image as input. The model processes the image and returns prediction values. The application then interprets those values and displays meaningful results.
The overall workflow looks like this:
Obtain a trained machine learning model.
Load the model into the Windows ML runtime.
Select an appropriate execution provider.
Prepare the model input.
Execute inference.
Read and interpret the output.
Windows ML supports ONNX models, making it possible to use models created with different machine learning frameworks, provided they are exported to a compatible ONNX format.
What Is ONNX?
ONNX stands for Open Neural Network Exchange.
It is an open format for representing machine learning models. ONNX provides a standardized way to describe model operations, inputs, outputs, and parameters.
This separation between model training and model execution is useful.
A data science team can train a model using a framework such as PyTorch and export it to ONNX. A C# developer can then use that model in a Windows application without needing to implement the original training framework.
For example, a model exported as:
Models/
image-classifier.onnx
can be included in a Windows application and loaded at runtime.
The ONNX file contains the model representation and learned parameters. It does not automatically contain every preprocessing or postprocessing step required by the original application.
Developers must understand the model's input and output requirements before integrating it.
Understanding the Windows ML Architecture
A typical Windows ML application contains several components.
<AsyncImage query="Microsoft Windows ML ONNX Runtime architecture diagram execution providers CPU GPU NPU Windows application" aspectRatio="16:9" width="100%" />
Component | Responsibility |
|---|
C# application | Manages model loading, input preparation, and result handling |
ONNX model | Contains the trained machine learning model |
Windows ML runtime | Manages model execution |
Execution provider | Connects inference to supported hardware |
CPU, GPU, or NPU | Performs the model computations |
The application does not need to manage every hardware-specific implementation itself.
Windows ML helps discover and configure suitable execution providers. This makes it easier to run the same model across different Windows devices.
However, actual hardware acceleration depends on the model's operators, device capabilities, drivers, and available execution providers.
A model that runs successfully on one device may use a different execution provider on another device.
Preparing the Development Environment
Before writing code, prepare a Windows development environment.
You will need:
A supported Windows version.
Visual Studio with the Windows application development workload.
A compatible .NET SDK.
Windows ML packages and APIs.
A compatible ONNX model.
For a new C# desktop application, you can use a Windows App SDK project.
A WinUI 3 application is a practical choice because it provides a modern Windows desktop interface while allowing you to write application logic in C#.
You can also integrate Windows ML into an existing supported Windows application.
Create a C# Windows Application
Create a new WinUI 3 application in Visual Studio.
Choose a suitable project name, such as:
WindowsMLDemo
Organize the project so that the model and inference-related code remain separate from the user interface.
For example:
WindowsMLDemo/
Models/
image-classifier.onnx
Services/
ImageInferenceService.cs
ViewModels/
MainViewModel.cs
MainWindow.xaml
MainWindow.xaml.cs
This structure keeps model execution independent of the presentation layer.
Add Windows ML Dependencies
Windows ML provides APIs for loading and running ONNX models.
The package and API setup depends on the Windows ML distribution and target Windows version used by the project.
Use the current Windows ML documentation to select the supported package for your application rather than assuming that an older Microsoft.ML.OnnxRuntime package provides the complete Windows ML API.
This distinction matters because Windows ML is a Windows platform inference solution, while ONNX Runtime is a broader inference runtime with its own package and execution-provider configuration.
For a project using the Windows ML managed API, add the corresponding Windows ML NuGet dependency and configure the project for its supported Windows target.
Keep the model file in the project and configure it to be included in the application output or package.
Installing Windows ML in a C# Project
Windows ML provides two main deployment options for C# applications: self-contained and framework-dependent.
The choice affects application size, runtime updates, and deployment requirements.
Option 1: Self-Contained Deployment
For a project targeting Windows 10 build 18362 or later, install:
dotnet add package Microsoft.Windows.AI.MachineLearning
This package includes the Windows ML APIs and runtime binaries.
Another option is Microsoft.WindowsAppSDK.ML, which supports applications targeting Windows 10 build 17763 or later.
In self-contained deployment, the Windows ML runtime is included with the application. Users do not need a separately installed Windows ML runtime, but the application package becomes larger.
Option 2: Framework-Dependent Deployment
For framework-dependent deployment, install:
dotnet add package Microsoft.WindowsAppSDK.ML
dotnet add package Microsoft.WindowsAppSDK.Runtime
Alternatively, use the main Windows App SDK package version 1.8.1 or later, which includes Windows ML.
The Windows App SDK runtime must be available on the user's device. In return, the application can share the runtime instead of packaging another copy.
Consideration | Self-contained | Framework-dependent |
|---|
Runtime included with application | Yes | No |
Application size | Larger | Smaller |
Runtime updates | Controlled by application updates | Provided through Windows App SDK servicing |
Runtime installation dependency | No separate runtime dependency | Windows App SDK runtime required |
Version control | More direct | Depends on installed runtime |
Suitable for | Controlled enterprise deployments | Smaller application downloads |
For this example, use self-contained deployment so that the application carries its Windows ML runtime dependencies.
Do not install the main Microsoft.WindowsAppSDK or Microsoft.WindowsAppSDK.Runtime package when following the standalone self-contained package approach. Those packages change the deployment model.
Loading an ONNX Model From C#
After installing the dependency, add the ONNX model to the project.
For example:
WindowsMLDemo/
Models/
image-classifier.onnx
Services/
ImageInferenceService.cs
Configure the model file to be copied to the output directory.
In Visual Studio, select the ONNX file and configure its build action and copy behavior. Alternatively, add this configuration:
<ItemGroup>
<Content Include="Models\image-classifier.onnx">
<CopyToOutputDirectory>
PreserveNewest
</CopyToOutputDirectory>
</Content>
</ItemGroup>
The model will then be available alongside the application's output files.
Create an Inference Service
Windows ML includes a shared ONNX Runtime distribution.
In C#, you can use the same ONNX Runtime namespace and inference APIs used by standalone ONNX Runtime:
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
Create a service that loads the model:
using Microsoft.ML.OnnxRuntime;
public sealed class ImageInferenceService : IDisposable
{
private readonly InferenceSession _session;
public ImageInferenceService(string modelPath)
{
_session = new InferenceSession(modelPath);
}
public void Dispose()
{
_session.Dispose();
}
}
The InferenceSession represents a loaded model and provides the interface for executing inference.
Creating the session can involve model loading and initialization work. Therefore, avoid creating a new session every time the user performs an inference request.
Keep the session alive and reuse it for multiple predictions.
Understanding Model Inputs and Outputs
Before executing a model, understand its input and output contract.
An ONNX model may expect:
For example, an image classification model might expect an input tensor with this shape:
[1, 3, 224, 224]
The dimensions represent:
Dimension | Meaning |
|---|
1 | Batch size |
3 | Number of image channels |
224 | Image height |
224 | Image width |
This is only an example. Not every image classification model uses this shape or channel ordering.
You should inspect the actual ONNX model metadata and its documentation before preparing the input.
Inspect Model Metadata
You can inspect input and output names after creating the inference session:
using Microsoft.ML.OnnxRuntime;
public void PrintModelInformation()
{
foreach (var input in _session.InputMetadata)
{
Console.WriteLine($"Input: {input.Key}");
Console.WriteLine($"Type: {input.Value.ElementType}");
Console.WriteLine(
$"Dimensions: {string.Join(", ", input.Value.Dimensions)}");
}
foreach (var output in _session.OutputMetadata)
{
Console.WriteLine($"Output: {output.Key}");
}
}
This information helps identify the names and dimensions required when executing the model.
It is particularly useful when integrating a model obtained from another team or a model repository.
Running Inference With C#
Now let's execute the model.
For demonstration purposes, assume the model expects a single floating-point tensor with the shape [1, 3, 224, 224].
The following example creates an input tensor and passes it to the inference session.
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
public float[] Predict(float[] inputData)
{
const int expectedInputSize = 1 * 3 * 224 * 224;
if (inputData.Length != expectedInputSize)
{
throw new ArgumentException(
$"Expected {expectedInputSize} input values.",
nameof(inputData));
}
var inputTensor = new DenseTensor<float>(
inputData,
new[] { 1, 3, 224, 224 });
var inputName = _session.InputMetadata.Keys.First();
var inputs = new[]
{
NamedOnnxValue.CreateFromTensor(
inputName,
inputTensor)
};
using var results = _session.Run(inputs);
var output = results.First()
.AsTensor<float>()
.ToArray();
return output;
}
The method performs several operations.
First, it validates the input length. This prevents an incorrectly sized tensor from being passed to the model.
Next, it creates a DenseTensor<float> using the expected dimensions.
The input name is obtained from the model metadata. This example assumes the model has exactly one input.
The NamedOnnxValue object connects the tensor to the model's input name.
Finally, _session.Run(inputs) executes inference and returns the model outputs.
The output is converted into a regular C# array for further processing.
This example demonstrates the inference pipeline, not complete image preprocessing. A real image classifier also needs to resize the image, convert its pixels into the expected channel format, and apply the normalization specified by the model.
The output interpretation is also model-specific. Some models return class probabilities, while others return embeddings, bounding boxes, or multiple output tensors.
Preparing Image Data Before Inference
A common mistake is passing raw image bytes directly to an image classification model.
Most image models expect numerical tensors rather than JPEG or PNG file contents.
The preprocessing pipeline generally includes:
Loading the image.
Decoding its pixel data.
Resizing it to the model's expected dimensions.
Converting color channels into the required order.
Normalizing pixel values.
Creating the input tensor.
For example, one model may expect RGB values normalized to the range 0 to 1:
[
normalized = \frac{pixel}{255}
]
Another model may expect values normalized using channel-specific means and standard deviations:
[
normalized = \frac{pixel - mean}{standardDeviation}
]
Using the wrong normalization can produce poor predictions even when inference executes successfully.
Always follow the preprocessing requirements used during model training.
Reading and Interpreting Model Results
The model output is not necessarily a human-readable prediction.
For example, an image classification model might return an array containing confidence scores for several classes.
A simplified output could look like this:
0.02
0.91
0.04
0.03
These values represent model outputs associated with different classes.
If the model uses a softmax output, the values may represent normalized class probabilities. However, not every model produces probabilities, so check the model's output definition.
A basic application might identify the highest-scoring class:
public static int GetHighestScoringClass(float[] scores)
{
if (scores.Length == 0)
{
throw new ArgumentException(
"The prediction output is empty.");
}
return Array.IndexOf(scores, scores.Max());
}
The returned index must be mapped to the correct class label.
For example, if the model's label file contains:
0 - Cat
1 - Dog
2 - Horse
3 - Bird
An output index of 1 represents the Dog class.
Keep the label mapping and model version together. If the model changes its class ordering, the application must use the matching labels.
Selecting Hardware Acceleration
One of the main benefits of Windows ML is its ability to work with different hardware execution providers.
An execution provider is responsible for executing supported model operations on a particular compute backend.
Windows ML includes CPU execution and legacy DirectML support. Additional hardware-specific providers can be acquired on supported systems.
The available providers depend on the Windows ML version, Windows version, hardware, and drivers.
CPU Execution
CPU execution is the simplest starting point.
The Windows ML runtime includes the ONNX Runtime CPU execution provider.
For a basic inference session:
using Microsoft.ML.OnnxRuntime;
using var session = new InferenceSession(modelPath);
This provides a straightforward way to verify that the model loads and executes correctly before introducing hardware-specific dependencies.
CPU execution is useful when:
The model is relatively small.
Hardware acceleration is unavailable.
Device compatibility is important.
Inference workloads are not computationally intensive.
GPU Execution
GPU execution can improve performance for supported image, video, and other compute-intensive models.
Windows ML provides execution-provider options for supported GPU hardware.
Available providers include:
Provider | Typical hardware |
|---|
DirectML | Compatible DirectX 12 GPUs |
AMD GPU | Supported AMD GPUs |
NvTensorRtRtx | Supported NVIDIA GPUs |
OpenVINO | Supported Intel hardware |
QNN | Supported Qualcomm hardware |
The provider must support the model's operators, data types, and tensor shapes.
Do not assume that a GPU will execute every model operation. The runtime may partition the model graph between supported providers and CPU fallback, depending on configuration.
NPU Execution
An NPU is a Neural Processing Unit designed for AI workloads.
NPUs can be particularly useful for sustained local inference with lower power consumption.
Windows ML supports hardware-specific NPU providers, including:
OpenVINO for supported Intel hardware.
QNN for supported Qualcomm hardware.
VitisAI for supported AMD hardware.
NPU support depends on device compatibility and driver requirements.
A device having an NPU does not automatically mean that every ONNX model can execute entirely on that NPU.
Check the provider's operator support and model compatibility before selecting it for production.
Managing Execution Providers
Windows ML provides the ExecutionProviderCatalog APIs for acquiring Windows-certified execution providers.
This is useful when an application needs to discover and use hardware-specific acceleration without distributing every vendor provider itself.
The general workflow is:
Check which execution providers are available.
Acquire the required provider.
Register the provider with the ONNX Runtime session.
Create the inference session.
Execute the model.
An important distinction is that Windows ML execution providers are not all included in the base runtime.
Some providers are downloaded on demand through the catalog, while developers can also bring their own provider binaries.
For applications that must operate in offline or managed enterprise environments, bringing and controlling provider binaries may be more appropriate.
Do not hardcode the assumption that a particular vendor provider is available on every Windows computer.
Compiling and Caching Models
Some execution providers benefit from model compilation before inference.
Compilation prepares the model for the target hardware and can improve subsequent inference performance.
Windows ML includes the ONNX Runtime compilation APIs.
For example:
using Microsoft.ML.OnnxRuntime;
public static void CompileModel(
string modelPath,
string compiledModelPath)
{
using var sessionOptions = new SessionOptions();
using var compileOptions =
new OrtModelCompilationOptions(sessionOptions);
compileOptions.SetInputModelPath(modelPath);
compileOptions.SetOutputModelPath(compiledModelPath);
compileOptions.CompileModel();
}
The exact compilation behavior depends on the selected execution provider.
Model compilation can take several seconds or even several minutes.
For this reason, do not run compilation on the UI thread.
A better approach is to compile the model during an appropriate initialization or preparation phase, then reuse the compiled artifact.
Store compiled models in application-local storage and associate them with the relevant model and provider versions.
If the model, execution provider, or runtime changes, the compiled artifact may need to be regenerated.
Keeping the Windows UI Responsive
Inference can consume significant CPU, GPU, or NPU resources.
If inference executes synchronously on the UI thread, the application may become unresponsive while the model processes the input.
This can affect user experience, especially when models are large or input data requires extensive preprocessing.
Move inference work away from the UI thread.
For example:
private async Task RunPredictionAsync(float[] inputData)
{
try
{
var result = await Task.Run(
() => _inferenceService.Predict(inputData));
// Update the UI through the application's UI dispatcher.
DisplayPrediction(result);
}
catch (Exception ex)
{
DisplayError(ex.Message);
}
}
The inference operation runs on a background thread, allowing the UI to remain responsive.
In a production application, also consider cancellation, duplicate requests, progress indicators, and memory usage.
Avoid creating multiple inference sessions for every button click. Reuse a properly managed session when possible.
Handling Errors During Local Inference
Local model execution can fail for several reasons.
Some problems occur during model loading, while others appear only when the application executes inference.
Problem | Possible reason | Recommended action |
|---|
Model file not found | Incorrect model path or packaging configuration | Verify the published model location |
Model loading fails | Unsupported ONNX operator or incompatible model | Validate the model with the selected runtime |
Input shape error | Tensor dimensions do not match the model | Inspect model metadata |
Invalid input type | Model expects a different tensor data type | Match the input type to the ONNX definition |
Poor prediction results | Incorrect preprocessing or label mapping | Follow the model's preprocessing contract |
GPU provider unavailable | Missing provider, driver, or compatible hardware | Check provider availability and use CPU fallback |
NPU execution fails | Unsupported operator or incompatible device | Review provider compatibility |
Application becomes unresponsive | Inference is running on the UI thread | Move inference to background execution |
High memory usage | Repeated session creation or large tensors | Reuse sessions and dispose resources properly |
Handle exceptions at the service boundary and log enough information to diagnose failures without exposing sensitive input data.
A production application should also have a fallback strategy when hardware acceleration is unavailable.
Best Practices for Production Applications
Start With CPU Inference
Begin by running the model on the CPU.
This confirms that the model file, input tensor, output processing, and application integration are correct.
After establishing a working baseline, evaluate GPU or NPU acceleration.
Validate Model Compatibility
Do not assume that every ONNX model works with every execution provider.
Validate the model's operators, data types, shapes, and supported operations.
Test the model on representative hardware before selecting a provider for production.
Reuse Inference Sessions
Loading a model repeatedly can add unnecessary initialization overhead.
Create the inference session once and reuse it for multiple requests.
Dispose of the session when the application service is no longer needed.
Avoid Blocking the UI Thread
Run inference and model compilation as background operations.
Provide cancellation and progress feedback when processing takes a noticeable amount of time.
Cache Compiled Models
When using providers that benefit from compilation, generate the compiled model once and reuse it.
Avoid compiling the same model every time the application starts.
Monitor Memory and Battery Consumption
Local inference moves computation to the user's device.
Large models can consume substantial memory and processing resources.
Measure performance and battery usage on representative hardware rather than relying only on development-machine results.
Keep Model Versions Manageable
Treat models as versioned application dependencies.
Record the model version, expected input shape, preprocessing requirements, and output format.
When updating a model, validate the complete inference pipeline rather than replacing only the ONNX file.
Advantages and Disadvantages of Windows ML
Advantages | Disadvantages |
|---|
Runs inference locally | Requires model files and local hardware resources |
Can work without an internet connection after required components are available | Initial model and provider setup may be complex |
Supports CPU, GPU, and NPU execution providers | Hardware acceleration depends on device and driver compatibility |
Uses ONNX models from different training frameworks | Models must satisfy ONNX and provider compatibility requirements |
Reduces the need to send sensitive inputs to cloud services | Application packages can become larger |
Integrates with C# and the broader .NET ecosystem | Developers must manage preprocessing and output interpretation |
Supports reusable model sessions and compilation | Model compilation and caching require additional design |
Summary
Windows ML gives C# developers a practical way to add local machine learning inference to Windows desktop applications.
By using ONNX models and the ONNX Runtime APIs included with Windows ML, developers can load trained models, prepare input tensors, execute inference, and process predictions without sending every request to a cloud service.
The most important implementation steps are selecting a compatible model, installing the correct Windows ML package, understanding the model's input and output requirements, and creating a reusable inference session.
Start with CPU inference to establish a reliable baseline. Once the application works correctly, evaluate GPU or NPU execution providers based on the target devices and workload.
For production applications, pay particular attention to model compatibility, background execution, memory consumption, provider availability, model compilation, and deployment configuration.
With these practices, Windows ML can become a useful part of a C# application's architecture, especially when privacy, offline operation, and local processing are important requirements.
Join the conversation! Your thoughts help the community grow.