{"record":{"id":"58ea32ed388cbee3","repo":"microsoft/semantic-kernel","slug":"application-is-already-running","errorCode":null,"errorMessage":"Application is already running.","messagePattern":"Application is already running\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Agents/Runtime/Core/AgentsApp.cs","lineNumber":56,"sourceCode":"    /// <summary>\n    /// Gets the application lifetime object to manage startup and shutdown events.\n    /// </summary>\n    public IHostApplicationLifetime ApplicationLifetime => this.Services.GetRequiredService<IHostApplicationLifetime>();\n\n    /// <summary>\n    /// Gets the agent runtime responsible for handling agent messaging and operations.\n    /// </summary>\n    public IAgentRuntime AgentRuntime => this.Services.GetRequiredService<IAgentRuntime>();\n\n    /// <summary>\n    /// Starts the application by initiating the host.\n    /// Throws an exception if the application is already running.\n    /// </summary>\n    public async ValueTask StartAsync()\n    {\n        if (Interlocked.Exchange(ref this._runningCount, 1) != 0)\n        {\n            throw new InvalidOperationException(\"Application is already running.\");\n        }\n\n        await this.Host.StartAsync().ConfigureAwait(false);\n    }\n\n    /// <summary>\n    /// Shuts down the application by stopping the host.\n    /// Throws an exception if the application is not running.\n    /// </summary>\n    public async ValueTask ShutdownAsync()\n    {\n        if (Interlocked.Exchange(ref this._runningCount, 0) != 1)\n        {\n            throw new InvalidOperationException(\"Application is already stopped.\");\n        }\n\n        await this.Host.StopAsync().ConfigureAwait(false);\n    }","sourceCodeStart":38,"sourceCodeEnd":74,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/dotnet/src/Agents/Runtime/Core/AgentsApp.cs#L38-L74","documentation":"AgentsApp.StartAsync uses Interlocked.Exchange on _runningCount as a single-entry guard: if it was already 1, it throws InvalidOperationException. The app is a singleton-style host wrapper, so it may only be started once until ShutdownAsync resets the counter to 0.","triggerScenarios":"Calling StartAsync twice without an intervening ShutdownAsync; calling PublishMessageAsync (which auto-starts the host when _runningCount==0) and then explicitly calling StartAsync; a hosted-service/DI lifecycle starting the app and application code starting it again.","commonSituations":"Double initialization in ASP.NET host startup; mixing the auto-start path of PublishMessageAsync with an explicit StartAsync; retries that re-enter startup.","solutions":["Call StartAsync exactly once, or rely solely on PublishMessageAsync's auto-start and skip explicit StartAsync.","Guard with your own started flag or check the application lifetime state before calling StartAsync.","Ensure ShutdownAsync completes before attempting to restart."],"exampleFix":"// before\nawait app.StartAsync();\nawait app.PublishMessageAsync(msg, topic); // fine, already running\nawait app.StartAsync(); // throws\n\n// after\nawait app.StartAsync();\n// do not start again; publish directly\nawait app.PublishMessageAsync(msg, topic);","handlingStrategy":"validation","validationCode":"// AgentsApp exposes no public IsRunning; track via your own flag or rely on PublishMessageAsync auto-start.\nbool started = false;\nasync ValueTask EnsureStartedAsync(AgentsApp app)\n{\n    if (started) return;\n    try { await app.StartAsync(); started = true; }\n    catch (InvalidOperationException) { started = true; /* already running */ }\n}","typeGuard":null,"tryCatchPattern":"try { await app.StartAsync(); }\ncatch (InvalidOperationException) { /* already running; safe to continue publishing */ }","preventionTips":["Choose one startup strategy: either explicit StartAsync once, or rely on PublishMessageAsync auto-start.","Centralize app startup in composition root to avoid multiple callers starting.","Avoid calling StartAsync from concurrent initialization paths."],"tags":["agentsapp","lifecycle","startup","runtime","dotnet"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}