dotnet/machinelearning · error · InvalidOperationException

Start must be called on a ModelLoader before it can be used.

Error message

Start must be called on a ModelLoader before it can be used.

What it means

FileModelLoader.GetReloadToken throws InvalidOperationException because the loader has not been initialized by a call to Start. Start creates the _reloadToken (and _model) lazily; before that, these members are null and there is no change token to hand out. The library treats using an un-started loader as a programming error in the host application.

Source

Thrown at src/Microsoft.Extensions.ML/ModelLoaders/FileModelLoader.cs:97

                    Logger.ReloadingFile(_logger, _filePath, timer.Elapsed);
                }
                previousToken.OnReload();
                timer.Stop();
                Logger.FileReloadEnd(_logger, _filePath, timer.Elapsed);
            }
            catch (OperationCanceledException)
            {
                // This is a cancellation - if the app is shutting down we want to ignore it.
            }
            catch (Exception ex)
            {
                Logger.FileReloadError(_logger, _filePath, timer.Elapsed, ex);
            }
        }

        public override IChangeToken GetReloadToken()
        {
            if (_reloadToken == null) throw new InvalidOperationException("Start must be called on a ModelLoader before it can be used.");
            return _reloadToken;
        }

        public override ITransformer GetModel()
        {
            if (_model == null) throw new InvalidOperationException("Start must be called on a ModelLoader before it can be used.");

            return _model;
        }

        private FileStream WaitForFile(string fullPath, FileMode mode, FileAccess access, FileShare share)
        {
            for (int numTries = 0; numTries < 100; numTries++)
            {
                FileStream fs = null;
                try
                {
                    fs = new FileStream(fullPath, mode, access, share);

View on GitHub (pinned to 7b76e69cf9)

Solutions

  1. Call Start() on the FileModelLoader before any consumer accesses GetReloadToken(), typically during application startup (e.g. in Program.cs or a hosted service).
  2. If using the Microsoft.Extensions.ML abstractions, register the loader via the standard AddPredictionEnginePool/ModelLoader pipeline so Start is called automatically.
  3. If ordering is the issue, resolve the loader inside a hosted service that explicitly calls Start before subscribing to reload tokens.
  4. Alternatively switch to DirectoryModelLoader-based registration which manages lifecycle for you.

Example fix

// before
var loader = new FileModelLoader(logger, modelPath);
var token = loader.GetReloadToken(); // InvalidOperationException
// after
var loader = new FileModelLoader(logger, modelPath);
loader.Start();
var token = loader.GetReloadToken();
ChangeToken.OnChange(() => loader.GetReloadToken(), () => ReloadPredictor());
Defensive patterns

Strategy: try-catch

Validate before calling

if (loader is FileModelLoader fml && !fml.IsStarted)
    fml.Start();
var token = loader.GetReloadToken();

Try / catch

try
{
    var token = loader.GetReloadToken();
}
catch (InvalidOperationException ex) when (ex.Message.Contains("Start must be called"))
{
    loader.Start();
    var token = loader.GetReloadToken();
}

Prevention

When it happens

Trigger: Calling GetReloadToken() (directly or via a ChangeToken registration/OnChange subscription) before FileModelLoader.Start() has completed; resolving a ModelLoader from DI where only the loader was registered but Start was never invoked at startup.

Common situations: Custom startup code registering the loader but skipping Start(); DI service resolving the loader earlier than the hosted service that calls Start; race where an OnChange callback fires before initialization; refactoring away the hosted-service bootstrap that used to call Start.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of dotnet/machinelearning@7b76e69cf9 (2026-09-11). Data as JSON: /api/errors/50b4c03ea2358f33. Report an issue: GitHub.