Skip to main content
The InferenceSession class is the main entry point for running inference with ONNX models in C#.

Namespace

Class Declaration

Constructors

InferenceSession(string)

Constructs an InferenceSession from a model file.
Parameters:
  • modelPath (string): Path to the ONNX or ORT model file
Example:

InferenceSession(string, SessionOptions)

Constructs an InferenceSession with custom session options.
Parameters:
  • modelPath (string): Path to the model file
  • options (SessionOptions): Session configuration options
Example:

InferenceSession(byte[])

Constructs an InferenceSession from a model in a byte array.
Parameters:
  • model (byte[]): ONNX model as byte array
Example:

InferenceSession(byte[], SessionOptions)

Constructs an InferenceSession from bytes with custom options.

InferenceSession with PrePackedWeightsContainer

Constructs a session that shares pre-packed weights across multiple sessions.
Parameters:
  • modelPath (string): Path to the model
  • options (SessionOptions): Session options
  • prepackedWeightsContainer (PrePackedWeightsContainer): Shared weights container
Example:

Properties

InputMetadata

Gets metadata for input nodes.
Example:

InputNames

Gets ordered list of input names.
Example:

OutputMetadata

Gets metadata for output nodes.

OutputNames

Gets ordered list of output names.

OverridableInitializerMetadata

Gets metadata for overridable initializers.

Methods

Run

Runs inference on the model.

Run(IReadOnlyCollection<NamedOnnxValue>)

Parameters:
  • inputs: Collection of input tensors
Returns: Collection of output tensors Example:

Run(IReadOnlyCollection<NamedOnnxValue>, IReadOnlyCollection<string>)

Runs inference with specific output names.
Example:

Run(IReadOnlyCollection<NamedOnnxValue>, RunOptions)

Runs inference with custom run options.

RunAsync

Asynchronously runs inference.
Example:

GetMemoryInfosForInputs

Gets memory information for all inputs.

GetMemoryInfosForOutputs

Gets memory information for all outputs.

Dispose

Releases resources used by the session.
Best Practice:

Complete Example

Image Classification

Batch Processing

Thread Safety

The InferenceSession class is thread-safe for Run() operations. Multiple threads can call Run() concurrently on the same session instance.

Performance Tips

  1. Reuse sessions: Create session once, use many times
  2. Use SessionOptions: Configure optimizations appropriately
  3. Dispose properly: Always dispose sessions and results
  4. Batch when possible: Process multiple inputs together
  5. Use execution providers: Enable GPU acceleration when available

See Also