Chapter 21. Host Integration
The examples in the first twenty chapters all start from the same line, demo.Launch(). That one line builds the application and the host together. Address, port, logging, and the life and death of the process are all decided for you. For a local tool that is just right; but as soon as the application has to live in the same process as something else, that one line is no longer enough.
This chapter moves the workbench into an ASP.NET Core host and uses what the host provides. Business services in the container, values from configuration, logging, health checks, and a stopping process that can wind things down.
Look at the skeleton first. The example’s Program.cs no longer builds the application directly at the start; it builds the host first.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGradio();
// ...register this workbench's own services
var app = builder.Build();
The pages are still written with gr.Blocks(); once they are written, UseGradio mounts them into the host.
var demo = gr.Blocks(title: "Personal Local Workbench");
using (demo)
{
Home();
using (demo.Route("Text", "text")) { TextPage(); }
// ...the other eight pages
}
app.UseGradio(demo);
app.Run();
demo is still that demo, and the pages are still those pages. What changes is who owns the process. Before, it was Gradio’s standalone host; now it is your ASP.NET Core application.
Draw the boundary first. This chapter is about “mounting it in” and “what the host gives you”. Exposing capabilities as callable interfaces is Chapter 22. Authentication still works as it did in Chapter 20; this chapter does not cover it again.
21.1 Standalone Host and Self-Built Host
The first twenty chapters use a standalone host. demo.Launch() builds a web host internally that serves only this application, then holds the calling thread until the process is stopped. The address defaults to 127.0.0.1, the port defaults to 7860, and the framework configures logging itself. Apart from this UI, there is nothing else in this process. No endpoints of your own, no other background tasks, and no container that you decide.
The standalone host has a second form, where you build the host object yourself.
var options = new GradioServerOptions
{
ServerName = "127.0.0.1",
ServerPort = 7860,
HealthCheckPath = "/health",
};
await using var host = new GradioServer(options);
await host.StartAsync(default);
Console.WriteLine(host.BaseAddress);
await host.StopAsync(default);
GradioServer and Launch are the same set of things. It registers the same services and mounts the same route table; it simply spreads the options out and hands startup and shutdown back to you. When StartAsync returns, the service is already listening; when StopAsync returns, it has already stopped. The example’s lab project uses exactly this.
It builds its own container, so the pages have to be written before the host is built. What lab does is first write the pages with gr.Blocks(), then register that one into the container through ConfigureServices.
var page = gr.Blocks(title: "Host Playground: GradioServer");
using (page) { /* write the page */ }
var options = new GradioServerOptions
{
ConfigureServices = services => services.AddSingleton(page),
};
await using var host = new GradioServer(options);
After startup, print a line to check: ReferenceEquals(host.Blocks, page) is True. What the container serves really is the one just written, not an empty page it built on its own. Without this step, the pages are written onto an object nobody serves, and the browser opens to a blank page.
The third form is the main line of this chapter, the self-built host. The host is the ASP.NET Core application you build with WebApplication.CreateBuilder; Gradio is just one piece mounted onto it. Address, logging, container, endpoints, middleware — all of them are yours.
Launch also has a non-blocking use. gr.Launch(demo, preventThreadLock: true) returns the GradioServer to you and the calling thread keeps going. lab has verified it this way. The console first prints Running on local URL, followed immediately by a line Address returned by Launch: http://127.0.0.1:7864/; both are the same address. If you want to manage stopping yourself but do not want to touch GradioServerOptions, use this overload.
The three shapes side by side.
Figure 21-1 Three shapes, one and the same route table on the server side
How to choose depends on whether this process has anything else to do.
- Only this one UI, for your own use:
demo.Launch(). One line, nothing to manage. - Still only this UI, but you want health checks and want to control startup and shutdown yourself:
GradioServer. - This process also has other services, other endpoints, other background tasks: a self-built host.
The third form is not “more advanced” than the first two; only the ownership differs. In the first two, the process exists for the UI; in the third, the UI is part of the process. To put it another way: the first two are “make the UI into a program”, the third is “put a UI inside a program”.
The phrase “the same route table” has evidence you can check. The page list of the same workbench under a self-built host has ten entries. Home plus nine addresses, 527 components, 112 bindings. These numbers come from the application itself, not from the host. Changing hosts did not remove a single page, nor did it change authentication, theme, or upload directory; those are the application’s own settings, and the host does not alter them.
One easy misunderstanding: in a self-built host, do not call demo.Launch() again. It would build another host and hold the calling thread, and the host you wanted would never get to start. The example replaces the last line with app.Run(), which is ASP.NET Core’s own startup call.
21.2 Host Options and Listening Address
The standalone host has few options, but every one of them directly decides “who can connect”.
ServerName is the listening address, defaulting to 127.0.0.1, which only the local machine can connect to. Change it to 0.0.0.0 and it listens on all network cards, so machines on the same LAN can connect too. The console still prints only one address, but what actually opens is another door. This book is positioned for single-user use on one machine, so the examples stay on the loopback address by default; before letting others connect, think about whether the gate from Chapter 20 is enough.
ServerPort is the port, defaulting to 7860. Set it to 0 to let the operating system pick a free port. Which one it picked, read from BaseAddress after startup.
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://127.0.0.1:51010
BaseAddress = http://127.0.0.1:51010/
BaseAddress is “the address to hand out”. When the port is 0, it is the one the system actually gave, not 0. Automation scripts, screenshot tools, and the code that prints the address to the user should all read it rather than build it themselves.
When listening on 0.0.0.0, the log also prints http://0.0.0.0:7863. That is not an address for the browser. On the local machine you still open 127.0.0.1:7863; another machine has to use this machine’s LAN address. Both addresses point to the same process; the only difference is “who can connect in”.
The page in a standalone host looks like this.
Figure 21-2 The lab page uses the default theme, because this page sets no theme; appearance belongs to the application, not the host
HealthCheckPath gives the health check a path; if you do not set it, nothing is mounted. ConfigureLogging adjusts logging, and ConfigureServices adds things to the container before Gradio’s own registrations. The latter is the standalone host’s only extension point, and 21.4 uses a similar approach.
In a self-built host, these knobs are no longer given directly by code. Address and port come from ASP.NET Core configuration; the example writes them in appsettings.json.
{
"Urls": "http://127.0.0.1:7860"
}
The Urls key is read by the host, not by Gradio. It can also be overridden by the command line or an environment variable of the same name.
dotnet Chapter21.dll --urls http://127.0.0.1:7867
$env:Urls="http://127.0.0.1:7868"
Both were tested and take effect, on ports 7867 and 7868 respectively. But ASPNETCORE_URLS does not override the Urls in the file in this combination. When both are present, the one in the file wins. This is easy to remember backwards; when you go to change the port, take --urls as authoritative.
The port-conflict error is the same as before, only this time it is thrown at host startup.
System.IO.IOException: Failed to bind to address http://127.0.0.1:7860: address already in use.
In a self-built host, demo.Launch(serverPort: 7861) is no longer the way to change the port. That parameter belongs to the host Launch builds itself. To change the port, change Urls, or pass --urls at startup.
One last small thing: port 0 works well in both hosts. To run a second instance for comparison, or when a screenshot tool fears port conflicts, you can let it pick for itself and then read the actual port back from the log or BaseAddress.
21.3 Registering and Mounting in ASP.NET Core
The self-built host has only two calls.
builder.Services.AddGradio(); // kernel, application, route table
app.UseGradio(demo); // hand in the finished page, map the routes
AddGradio registers three things: the kernel for rendering and sessions, a Blocks, and that route table. The application is held by the container. One container hosts only one application — that is its constraint, not a suggestion. UseGradio maps the route table onto the host’s endpoints and tells the container “the pages to serve are these ones”.
It does not provide an address, does not provide TLS, does not provide a reverse proxy, and does not decide where logs go for you. It only gets done the one thing “Gradio needs a container and a route table”; the rest belongs to the host. The other way around, the middleware the host already has (HTTPS, compression, rate limiting, static files) can all be added to this pipeline, and Gradio does not block it.
The order has to be spelled out, because the order the documentation gives does not work. The documentation says “first mount the routes, then write the UI into the application, finally start”, which corresponds to this.
app.UseGradio(); // map the routes first
var demo = app.Services.GetRequiredService<Blocks>();
using (demo) { gr.Textbox(...); } // then write the UI
Written this way, it throws as soon as the first button binds an event.
System.InvalidOperationException: An event binding has to belong to an application.
Bind it on a block that was added to a Blocks, or merge its triggers with Blocks.On first.
Factories such as gr.Textbox() write a line onto the page that is currently open. What opens that page is gr.Blocks(), which opens the rendering scope at the same time as it returns the application; using closes it when it ends. The Blocks in the container has not gone through this step, has no open rendering scope, so the factory cannot write into it; components then have no owner, and a binding naturally cannot find an application.
So the example uses a different overload: write the pages first, then let the host mount them.
var demo = gr.Blocks(title: "Personal Local Workbench");
using (demo) { /* home page and nine pages */ }
app.UseGradio(demo);
The example puts builder.Build() before writing the pages, because the handler functions need IServiceScopeFactory from the container; conversely, writing the pages before Build is also fine, as long as the services needed are already available then. Both orders work; the only thing that cannot change is “pages before UseGradio”.
UseGradio(demo) does two things. It registers this one page into the container, then maps the route table onto it. It must be called before the container resolves its own Blocks. Two applications living in one container is something it explicitly refuses. In the example it comes immediately after the pages, with nothing else touching the container in between.
Once mounted, the host’s own endpoints are written as usual.
app.MapGradioHealth("/health");
app.MapGet("/ping", (HostFacts facts) => Results.Text($"pong {facts.Address}"));
app.MapPost("/stop", (IHostApplicationLifetime lifetime) =>
{
lifetime.StopApplication();
return Results.Text("stopping");
});
/ping is the host’s own endpoint; it shares one address and one container with the workbench, but it is not in Gradio’s route table. That means two things: it is not protected by demo.Auth, and it does not go into /gradio_api/info. The example keeps it so that “two things in one process” is visible; when a real application adds its own endpoints, it has to put its own gate on them. The gate from Chapter 20 only covers Gradio’s pages and interfaces.
/stop is the switch used for verification in this chapter; it calls the very method Ctrl+C calls. A real application should not leave it in.
UseGradio only maps Gradio’s routes; the endpoints you map yourself still belong to you. The two share one address and are told apart by path. The health check is placed after UseGradio(demo) because it has to resolve the Blocks in the container, and the pages are only handed in at the moment of UseGradio(demo). Reverse the order and the check registers that empty application instead.
app.Run() blocks until the process stops, so statements written after it never execute. Things that have to happen only after startup go into the ApplicationStarted callback; 21.7 uses this.
After startup, the console no longer shows that one line Running on local URL, but a series of the host’s own.
info: Chapter21.Heartbeat[0]
Heartbeat started
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://127.0.0.1:7860
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: xxx
info: Chapter21[0]
Workbench started: http://127.0.0.1:7860
The address is still that address, and the pages are still those pages.
Figure 21-3 The home page under a self-built host: ten items in the navigation, the same as with a standalone host
After mounting, not one of the workbench’s own settings has moved. Theme, Auth, UploadFolder, and the queue limit are still the values assigned to demo when the pages were written. The host does not know them and does not need to. That is exactly what “the UI is part of the process” means. The process provides the container and the address; the application decides what it looks like.
After mounting, the workbench’s main flows have to be walked through again before they count. The example got these working under a self-built host. The login card appears as usual, and the right password lets you in; all ten pages open; uploads, events, and the queue are all still in their original places. None of this is automatic. If UseGradio registers one page too few, or registers it too late, the UI is empty or the process simply exits.
21.4 Dependency Injection and Business Services
Up to this chapter, handler functions have always been “use whatever is in the closure”. Chapter 3 covered where their parameters come from. Components in inputs give values by position, and Request, Progress, CancellationToken are injected by the framework by type. Beyond that, it does not know the container and will not resolve a service for you.
So “using dependency injection” has only one path in Gradio.NET. Take the service out of the container and pass it into the handler function’s closure. There are two ways to take it; the difference is “when you take it”.
The first takes it once, while writing the pages.
var desk = app.Services.GetRequiredService<WorkDesk>();
run.Click((string text) => desk.Arrange(text), [text], [body], apiName: "Clean up");
What this gets is an instance from the root container; the effect is the same as turning it into a singleton, with all sessions sharing one. In development the container stops you on the spot (scope validation); in production it gives you an instance that is never released. Neither is what you want.
The second is what the example uses. Take only the scope factory, and open a scope on each call.
var scopes = app.Services.GetRequiredService<IServiceScopeFactory>();
(object, string) DeskArrange(string text, double? width)
{
using var scope = scopes.CreateScope();
var desk = scope.ServiceProvider.GetRequiredService<WorkDesk>();
var ledger = scope.ServiceProvider.GetRequiredService<RunLedger>();
var columns = width is null or <= 0 ? (int?)null : (int)Math.Round(width.Value);
var result = desk.Arrange(text, columns);
var nth = ledger.Record("Clean up");
return (result.Text, $"**Run {nth}** · Service instance `{result.Instance}`\n\n{result.Report}");
}
using guarantees the scope is released when this call ends. WorkDesk is Scoped, one instance per call; RunLedger is Singleton, shared across calls. Both services are taken from the same scope, written the same way; the lifetime is decided when they are registered.
Take the scope factory rather than IServiceProvider directly, because the scope has to be drawn by you: CreateScope() is on the factory, and the root container does not open one for you. Taking a Scoped service from the root container either gets stopped by the container or gives you an instance that is never released.
Those two columns lines are what the word “adaptation” concretely looks like. The component gives a double?, where 0 means “use the configuration”; the service wants an int?, where null means “not specified”. The translation sits in the handler function, and the service only knows its own contract.
WorkDesk itself looks like this.
public sealed class WorkDesk(IOptionsSnapshot<WorkbenchOptions> options, ILogger<WorkDesk> log)
{
private static int _instances;
public string Instance { get; } = $"WorkDesk#{Interlocked.Increment(ref _instances)}";
public WorkResult Arrange(string? text, int? width)
{
var settings = options.Value;
var columns = width ?? settings.MaxWidth;
var result = TextLayout.Wrap(text, columns);
log.LogInformation("Clean up {Chars} characters, {Lines} lines, at most {Width} characters per line",
text?.Length ?? 0, result.Report.Lines, columns);
var report = $"{result.Report.Lines} lines, {result.Report.Characters} characters, longest line {result.Report.LongestLine} characters";
// ...
return new WorkResult(result.Text, report, Instance);
}
}
It does only three things: read configuration, call the wrapping rules in core, and write one log line. The wrapping rules themselves stay in Chapter21.Core, a project that does not reference Gradio.NET; switching to a console app, a Web API, or another UI needs no change there. The handler function is the adaptation layer: open a scope, call, and lay the result out as the type the component wants.
The handler function’s parameter list can still write Request. It is injected by the framework by type, while the service is taken from a scope by the closure; the two paths do not conflict. Request answers “who is operating”, the service answers “how the work is done”. That identity-asking button in Chapter 20 used only Request; add the service as well and both can exist together, with no change to the parameter list.
The effect is visible on the page.
Figure 21-4 The host page: on the left the result from the business service, on the right the material from the container and configuration
Click the same button three times and the service instances are WorkDesk#1, WorkDesk#2, WorkDesk#3 in turn, while the “Record” count climbs from 1 to 2, 3. One is per-call, the other spans calls. The background task’s counter is climbing too; that is a different thread of things, covered in 21.7.
Several easy places to go wrong, all of the “it runs but it is not right” kind.
- Store a Scoped service in the closure. The pages are written only once and the closure lives until the process ends; that “one per call” service becomes a resident object, and it is released after the first request anyway, so using it again throws “already disposed”.
- Take a Scoped service straight from the root container. In development the container stops you; once scope validation is turned off, you get an instance that is never released.
- Forget to release the scope. You cannot see it once or twice; run it for a day and you have a pile of unreleased objects.
usingis the least troublesome way to write it. - Inject Scoped into Singleton. Again “a resident object holding a one-shot object”; the container refuses outright, which is better than finding out at runtime.
Separate two kinds of “once” as well. State from Chapter 14 counts by session, one per page load; the Scoped service here counts by call, one per button press. They are not the same thing. Put session data in a Scoped service and it is gone on the next call; put call parameters in State and they stay until the page closes.
One more thing that is not part of dependency injection but is often mentioned together with it. Do not push business logic back into the handler function. The handler function’s job is to translate the values the component gives into the parameters the service wants, then translate the service’s result into the type the component wants. Anything beyond translation (rules, computation, reads and writes) belongs to the service. The direct benefit is that the “parameter and return value contract” from Chapter 3 affects only this translation layer, and the rules themselves can be reasoned about on their own.
21.5 Providing Configuration to Handler Functions
Configuration comes in from the host, and the path is fixed: configuration source → IConfiguration → strongly typed options → service → handler function.
The example’s configuration looks like this.
{
"Workbench": {
"Owner": "Local user",
"Greeting": "This workbench is now hosted in an ASP.NET Core host.",
"MaxWidth": 24,
"Token": ""
}
}
Bind it into a type.
builder.Services.Configure<WorkbenchOptions>(builder.Configuration.GetSection("Workbench"));
After that any service can inject IOptions<WorkbenchOptions>, IOptionsSnapshot<WorkbenchOptions>, or IOptionsMonitor<WorkbenchOptions>. The three read values at different times. IOptions computes once, IOptionsSnapshot once per scope, and IOptionsMonitor can change on every read. WorkDesk uses Snapshot, one per call, which fits exactly.
The cost of choosing wrong is concrete. IOptions fixes the value at the first resolution, so editing the file has no effect and it looks like “hot reload is broken”; IOptionsMonitor can change on every read, which suits Singleton, but reading twice in one request can give two values and produce self-contradictory results. A Scoped service with Snapshot gets one per scope, consistent front to back.
One rule to remember about configuration source priority: a source added later overrides earlier ones. The default order is appsettings.json, appsettings.{environment}.json, environment variables, command line. Therefore.
$env:Workbench__MaxWidth="12"
dotnet run --project samples-en\chapter21\Chapter21.csproj
The “at most 12 characters per line” on the page comes from the environment variable; the 24 in the file is overridden. The two underscores are the separator for nested keys, so Workbench__MaxWidth corresponds to Workbench:MaxWidth.
Editing the file also takes effect, with no restart. After startup the example changes MaxWidth in appsettings.json from 24 to 16; the next button click wraps at 16.
**Configuration** Owner Local user · at most 16 characters per line · Password Configured (27 characters)
This holds only in services that “re-read on every call”. The password for demo.Auth is read from builder.Configuration while the pages are being written, so editing the file will not change it. Values like that need a restart to change. Splitting configuration into “hot” and “cold” is more useful than vaguely saying “hot reload is supported”. Hot means re-read on every call (MaxWidth); cold means read once while writing the pages (Greeting, AuthMessage, the authentication password). The former takes effect when you edit the file; the latter needs a restart.
The environment name also affects which file is read. appsettings.Production.json overrides appsettings.json, and appsettings.Development.json is layered on only when ASPNETCORE_ENVIRONMENT=Development. The example has neither file, so the Hosting environment: Production line in the log is the default.
You can also read configuration while writing the pages. builder.Configuration["Workbench:Greeting"] is available even before builder.Build(); the example’s Greeting and AuthMessage are both read this way. Its difference from IOptions is “how many times it reads”. Writing the pages reads once; a service may re-read on every call.
Once configuration reaches the handler function, keep one more rule: do not print sensitive items. The example’s Token shows only “whether it is configured” and its length.
var token = string.IsNullOrEmpty(options.Token) ? "Not configured" : $"Configured ({options.Token.Length} characters)";
Its value appears nowhere in the page, the log, or API responses. What the log records are numbers like “Clean up 22 characters, 1 line, at most 24 characters per line”, not the source text and not the password. This is not fussiness. Logs get copied, pasted into chat windows, and folded into issue reports; one casual extra line carries the credentials out with it.
appsettings.json should not hold real credentials either. It is a file that travels with the source, so once committed it is in the history. The example leaves it empty and the real value goes through an environment variable; Chapter 16 used the same approach when connecting to a model service.
The Error popup is another outlet. Its message is displayed as raw HTML; splicing configuration values into it is the same as sending credentials to the page. When you need to report an error, report the key name, not the value.
The whole path configuration takes into the handler function.
Figure 21-5 Configuration is read in the host, services are taken from the container per call, and the handler function only translates
Greeting and AuthMessage take a different path. They are read once while the pages are being written and become text on the page directly. So changing a sentence needs a restart, but what that buys you is “the same page code, a different set of copy when you change hosts”.
21.6 Host Logging Configuration and the Health Check Endpoint
Logging is configured on the host side; Gradio does not set up a separate one. The example’s appsettings.json adjusts only three levels.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Gradio.Net": "Information"
}
}
}
Push Microsoft.AspNetCore down to Warning and the request logs disappear. During local debugging that string of “Request starting / Request finished” is noisy; once it is suppressed, what remains is the application’s own words. Gradio.Net stays at Information so you can see it when the queue or routing goes wrong. For finer control, keep adding by category name, for example setting only Gradio.Net.GradioQueue to Debug.
What you can see in the log is the source of several conclusions in this chapter: the startup address, the heartbeat starting and stopping, the character and line counts of each cleanup, and a long task receiving cancellation. None of them contain source text or credentials.
A lower level is not always better. Debug prints request details, including things you do not want to keep; Warning swallows the startup information too, so when something breaks you cannot even see the address. Information is the default level and the one the example uses.
Gradio’s own logs are under the Gradio.Net.* category. When a binding fails, the queue writes a fail: line with the exception and the call stack together. That “Number received an empty string” line during the example’s debugging was seen from here. It is far more useful than the “something went wrong” line on the page, so do not push this category below Warning.
Health checks are another matter; you have to turn them on explicitly.
builder.Services.AddGradioHealthChecks(); // register the checks
app.MapGradioHealth("/health"); // give it a path
Once enabled, GET /health returns 200 and one line of plain text Healthy. It checks two things: that the pages are written and that the queue is up. Both have to hold before it counts as healthy. A host that only listens but has not written its pages, and a host whose queue is not up, should neither be sent traffic.
These two conditions are hard not to satisfy on a local machine, so what you normally see is always Healthy. Its value is in automated environments. An orchestrator probes once during the few hundred milliseconds after the process comes up, and sends no traffic if it is not healthy.
The framework’s response supports three levels, Healthy, Degraded, and Unhealthy; this check returns Healthy only when both conditions hold, otherwise Unhealthy. What it returns is plain text, not JSON. The probe looks only at the status code, not the body. How often to probe and how long before timeout are set by the orchestrator, not the application; local development does not need this endpoint at all, and its reader is the process manager.
This endpoint is opt-in. It is not in Gradio’s route table, and the Python version has no such route either; the framework does not add it by default so that “which paths this application exposes” stays countable. In the standalone host the counterpart is GradioServerOptions.HealthCheckPath; fill in a path and it registers and maps at the same time.
One more: health checks sit outside authentication. In the example, while logged out, /config returns 401 and /health returns 200. This is deliberate. Probes carry no cookie; put the health check behind the gate and the orchestrator will never see healthy. It returns only Healthy or Unhealthy and leaks no page content.
21.7 Lifecycle and Graceful Shutdown
The host’s life and death are broadcast by IHostApplicationLifetime, at three moments: startup complete, stopping, and stopped.
app.Lifetime.ApplicationStarted.Register(() =>
{
hostFacts.Address = string.Join(" / ", app.Urls);
hostFacts.StartedAt = DateTimeOffset.Now;
app.Logger.LogInformation("Workbench started: {Address}", hostFacts.Address);
});
app.Lifetime.ApplicationStopping.Register(() => { /* wind down */ });
app.Lifetime.ApplicationStopped.Register(() => app.Logger.LogInformation("Host stopped"));
ApplicationStarted is the moment to get the actual address; app.Urls is empty before then. ApplicationStopping is the window for winding down. Connections are still there and background tasks have not stopped; you still have a chance to tell them “it is time to stop”.
Handler functions in the queue are not in this window. When the host stops, Gradio’s queue does not cancel the handler functions that are running for you; the process exits and they disappear with it, and finally is not guaranteed to run. Run it once in the most intuitive way and you can see it. Stop the host while a streaming task at one frame per second reaches frame 2; the task keeps emitting up to frame 7, then the process is gone and there is no winding-down line in the log.
Two things have to be told apart here: the SSE long connection and the run inside the queue. The connection belongs to the host and breaks as soon as the process stops; the run belongs to the queue, and nobody notifies it when the host stops. Losing the former is no loss; losing the latter leaves work half done.
To wind down, you have to prepare a marker yourself and cancel it in ApplicationStopping.
var stopping = new CancellationTokenSource();
app.Lifetime.ApplicationStopping.Register(() =>
{
app.Logger.LogInformation("Host is stopping: cancelling long tasks, background tasks are winding down, connections close afterwards");
stopping.Cancel();
});
The handler function uses this marker together with the request’s own cancellation token.
async IAsyncEnumerable<string> LongRun([EnumeratorCancellation] CancellationToken token)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, stopping.Token);
for (var i = 1; i <= 20; i++)
{
var cancelled = false;
try
{
await Task.Delay(1000, linked.Token);
}
catch (OperationCanceledException)
{
cancelled = true;
}
if (cancelled)
{
app.Logger.LogWarning("Long task cancelled: request cancellation = {Requested}, host stopping = {Stopping}",
token.IsCancellationRequested, stopping.IsCancellationRequested);
yield break;
}
yield return $"Frame {i}, {DateTimeOffset.Now:HH:mm:ss}";
}
}
Two cancellation paths merge into one. Close the browser page and the request’s own token cancels; stop the host and stopping cancels. The handler function only knows linked and does not need to know who pressed it.
After the change, run the same scenario again and the log looks like this.
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
info: Chapter21[0]
Host is stopping: cancelling long tasks, background tasks are winding down, connections close afterwards
warn: Chapter21[0]
Long task cancelled: request cancellation = False, host stopping = True
info: Chapter21.Heartbeat[0]
Heartbeat stopped, 11 times in total
info: Chapter21[0]
Host stopped
From issuing the stop to the stream ending took 0.01 seconds. request cancellation = False shows that this time the host stopped the process.
The ApplicationStopping callback has to be short. It runs synchronously inside the stopping flow; do long work in it and the whole shutdown is held up by it.
Background tasks do not need you to cancel them. A BackgroundService’s stoppingToken comes from the host, StopAsync is called, and finally runs. The example’s heartbeat writes its total count in finally; that line “Heartbeat stopped, 11 times in total” is the evidence it ran.
The order of await using also matters. GradioServer.DisposeAsync stops the service first and then releases the container, so background tasks get a chance to finish finally; release the container first and the tasks do not even get a chance to wind down.
One more gate, the shutdown grace period. How long the host is willing to wait for running requests is decided by HostOptions.ShutdownTimeout, thirty seconds by default. The example changes it to five seconds.
builder.Services.Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(5));
What it governs is “how long the host is willing to wait”, not “cancel for you”. If a request ignores cancellation, it is cut off anyway when the five seconds are up. So the correct division of labour is: the application cancels by itself, and the grace period is only a fallback.
Cancellation is cooperative. Task.Delay, HttpClient, and stream reads and writes respond to it; pure computation does not. To make a loop cancellable, you have to check token inside the loop, or replace the slow step with a call that responds to cancellation. Chapter 17 covered this rule, and it holds just as well here for host shutdown.
Figure 21-6 The long task: after you click, the frames arrive one by one
The order of stopping.
Figure 21-7 After the stop signal arrives: first cancel, then stop the background tasks, finally release
Ctrl+C and the example’s /stop take the same path, both calling IHostApplicationLifetime.StopApplication(). The only difference is who pressed it. A real application deletes /stop and lets the stop be initiated by Ctrl+C or the process manager.
Finally, be clear about what stays and what disappears. Session state (Chapter 14) is in memory and is gone when the process goes; the upload cache (Chapter 12) is on disk, so the files remain when the process goes, to be collected by the cleanup schedule. The host does not decide these two things, but you need to know them when stopping.
21.8 Chapter Summary
After moving the workbench into an ASP.NET Core host.
- Three host shapes: one line of
Launch, a configurableGradioServer, and a self-builtAddGradio+UseGradio. All three use the same route table, and the page code does not change. - Address and port belong to the host. The standalone host reads
GradioServerOptions, the self-built host readsUrls(or--urlsat startup). Port 0 lets the system pick, and you read the actual value fromBaseAddressor the log. - The mounting order is “write the pages first, then hand them in”.
gr.Blocks()opens a rendering scope; theBlocksin the container does not. Write it the other way round and the first button’s event binding reports “does not belong to any application”. - Take services from the container per call. Take only
IServiceScopeFactoryand open a scope on each call. Scoped is one per call, Singleton is shared across calls; business rules stay incore, which does not reference Gradio.NET. - Configuration comes in from the host, credentials do not go out.
IOptionsSnapshotmeans editing the file needs no restart, and environment variables override the file; sensitive items show only their length, and logs record only numbers. - Winding down is up to you. Handler functions in the queue are not on the host’s shutdown chain; you cancel your own marker in
ApplicationStopping;BackgroundServiceis stopped correctly;ShutdownTimeoutis only a fallback.
One more boundary: a host is not a necessity. With only this one UI, for your own use alone, demo.Launch() remains the right choice. This chapter is about “what to do when it needs to live in the same process as something else”, not “every application should build its own host”.
The cost should be spelled out too. There is one more layer of host to maintain, one more configuration file to manage, and one more responsibility: “guard the endpoints you added yourself”. What you get in return is that this workbench can live in the same process as other services, using the same container, the same configuration, and the same logging, instead of an island that can only run on its own.
The amount of code in this chapter is not large; the hard part is ownership. Once you are clear about which things belong to the process and which to the application, the decisions after that fall into place.
When you wire the workbench into your own application, go through it in this order.
- Is there a line with the actual address in the startup log, matching
Urls; - Open a page while logged out and confirm it is still the login card;
/configis 401,/healthis 200; - Click a business button once and confirm the service instance changes and the count climbs;
- Change a value in
appsettings.jsonand click again to confirm the new value takes effect; - If you added the host’s own endpoints, confirm whether they need a gate. Gradio’s authentication does not cover them;
- Click the long task, stop the host, and confirm the log has both the cancellation line and the heartbeat-stopped line, and the process exits cleanly.
The next chapter is the last chapter of the book. Chapter 22 exposes the capabilities behind the UI as callable interfaces.