fix(macos): 模型窗口改由主线程承载,修复启动模型失败与后端崩溃 #29
No files matched your search
+31
-4
@@ -39,6 +39,7 @@ internal static class FlutterShell
|
||||
if (uiPath == null) return false;
|
||||
|
||||
var port = Port;
|
||||
AvaloniaHost? uiHost = null;
|
||||
|
||||
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
|
||||
if (!IsHealthy(port))
|
||||
@@ -50,13 +51,14 @@ internal static class FlutterShell
|
||||
|
||||
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
|
||||
{
|
||||
var app = TryStartBackend(args, candidate);
|
||||
var app = TryStartBackend(args, candidate, out var host);
|
||||
if (app == null) continue;
|
||||
|
||||
if (WaitHealthy(candidate, TimeSpan.FromSeconds(25)))
|
||||
{
|
||||
port = candidate;
|
||||
_backend = app;
|
||||
uiHost = host;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -76,7 +78,29 @@ internal static class FlutterShell
|
||||
return false;
|
||||
}
|
||||
|
||||
ui.WaitForExit();
|
||||
// 前端窗口已拉起。模型窗口由 Avalonia 承载,而 macOS 的 AppKit 要求
|
||||
// NSApplication 必须在**主线程**——所以事件循环要跑在这里(当前正是主线程),
|
||||
// 不能再丢到副线程,否则一点「启动模型」就会把整个后端带崩。
|
||||
ui.EnableRaisingEvents = true;
|
||||
var closed = 0;
|
||||
void RequestClose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref closed, 1) == 1) return;
|
||||
uiHost?.Shutdown();
|
||||
}
|
||||
|
||||
ui.Exited += (_, _) => RequestClose();
|
||||
if (ui.HasExited) RequestClose();
|
||||
|
||||
if (!ui.HasExited && uiHost != null)
|
||||
{
|
||||
// 阻塞直到界面退出(或图形环境初始化失败)。
|
||||
uiHost.RunOnCurrentThread();
|
||||
}
|
||||
|
||||
// Avalonia 起不来(无桌面会话)时仍要等界面退出,避免后端被提前收掉。
|
||||
if (!ui.HasExited) ui.WaitForExit();
|
||||
|
||||
StopBackend(_backend);
|
||||
_backend = null;
|
||||
return true;
|
||||
@@ -108,11 +132,14 @@ internal static class FlutterShell
|
||||
// ---------------------------------------------------------------- 进程管理
|
||||
|
||||
/// <summary>在本进程内启动后端;端口被占用等失败情况返回 null。</summary>
|
||||
private static WebApplication? TryStartBackend(string[] args, int port)
|
||||
/// <param name="uiHost">成功时交出模型窗口宿主,由调用方在主线程跑事件循环。</param>
|
||||
private static WebApplication? TryStartBackend(string[] args, int port, out AvaloniaHost? uiHost)
|
||||
{
|
||||
uiHost = null;
|
||||
try
|
||||
{
|
||||
var app = BackendServer.Start(args, port);
|
||||
var app = BackendServer.Start(args, port, out var host);
|
||||
uiHost = host;
|
||||
app.StartAsync().GetAwaiter().GetResult();
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,9 @@ public sealed class AvaloniaHost
|
||||
private readonly AppServices _services;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Task<bool>? _startTask;
|
||||
private readonly TaskCompletionSource<bool> _ready =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _started;
|
||||
|
||||
public AvaloniaHost(AppServices services) => _services = services;
|
||||
|
||||
@@ -37,56 +39,60 @@ public sealed class AvaloniaHost
|
||||
|
||||
public string? LastError { get; private set; }
|
||||
|
||||
public Task<bool> EnsureStartedAsync()
|
||||
/// <summary>
|
||||
/// 后端线程调用:等待「主线程已把 Avalonia 事件循环跑起来」。
|
||||
///
|
||||
/// 关键点:macOS 的 AppKit 要求 NSApplication 在**主线程**。以前这里把
|
||||
/// <c>StartWithClassicDesktopLifetime</c> 丢到一个新建的后台线程里跑,在 macOS 上
|
||||
/// 会直接崩掉整个后端进程(表现为点「启动模型」界面无反应、随后后端消失)。
|
||||
/// 现在改为由启动器在主线程调用 <see cref="RunOnCurrentThread"/>,
|
||||
/// 这里只等待就绪信号。
|
||||
/// </summary>
|
||||
public Task<bool> EnsureStartedAsync() => _ready.Task;
|
||||
|
||||
/// <summary>
|
||||
/// 必须在 UI 主线程调用。启动 Avalonia 桌面生命周期并阻塞,直到 <see cref="Shutdown"/>。
|
||||
/// 返回后(或初始化失败后)调用方负责收尾。
|
||||
/// </summary>
|
||||
public void RunOnCurrentThread()
|
||||
{
|
||||
lock (_gate)
|
||||
if (Interlocked.Exchange(ref _started, 1) == 1) return;
|
||||
|
||||
try
|
||||
{
|
||||
_startTask ??= Task.Run(StartCore);
|
||||
return _startTask;
|
||||
AppBuilder.Configure<HostApp>()
|
||||
.UsePlatformDetect()
|
||||
.AfterSetup(_ =>
|
||||
{
|
||||
IsAvailable = true;
|
||||
_ready.TrySetResult(true);
|
||||
})
|
||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
|
||||
LastError = ex.Message;
|
||||
_ready.TrySetResult(false);
|
||||
}
|
||||
}
|
||||
|
||||
private bool StartCore()
|
||||
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
|
||||
public void Shutdown()
|
||||
{
|
||||
var ready = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
var thread = new Thread(() =>
|
||||
if (_started == 0) return;
|
||||
try
|
||||
{
|
||||
try
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
AppBuilder.Configure<HostApp>()
|
||||
.UsePlatformDetect()
|
||||
.AfterSetup(_ => ready.TrySetResult(true))
|
||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastError = ex.Message;
|
||||
ready.TrySetResult(false);
|
||||
}
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "gc-ui-avalonia"
|
||||
};
|
||||
|
||||
// Windows 上 Avalonia 需要 STA 线程;macOS / Linux 不支持也不必要。
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
try { thread.SetApartmentState(ApartmentState.STA); }
|
||||
catch { /* 忽略:部分运行时不允许设置 */ }
|
||||
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
desktop.Shutdown();
|
||||
});
|
||||
}
|
||||
|
||||
thread.Start();
|
||||
|
||||
if (!ready.Task.Wait(TimeSpan.FromSeconds(30)))
|
||||
catch
|
||||
{
|
||||
LastError = "图形环境初始化超时";
|
||||
return false;
|
||||
// 事件循环尚未建立或已退出:无需处理
|
||||
}
|
||||
|
||||
IsAvailable = ready.Task.Result;
|
||||
return IsAvailable;
|
||||
}
|
||||
|
||||
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
||||
|
||||
@@ -30,19 +30,33 @@ public static class BackendServer
|
||||
{
|
||||
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
|
||||
public static WebApplication StartFromCommandLine(string[] args)
|
||||
=> Start(args, ResolvePort(args));
|
||||
=> Start(args, ResolvePort(args), out _);
|
||||
|
||||
/// <summary>同上,并交出模型窗口宿主(独立进程入口用:主线程留给 Avalonia)。</summary>
|
||||
public static WebApplication StartFromCommandLine(string[] args, out AvaloniaHost uiHost)
|
||||
=> Start(args, ResolvePort(args), out uiHost);
|
||||
|
||||
/// <summary>
|
||||
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
||||
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port)
|
||||
=> Start(args, port, out _);
|
||||
|
||||
/// <summary>
|
||||
/// 构建后端,并通过 <paramref name="uiHost"/> 交出模型窗口宿主。
|
||||
///
|
||||
/// 调用方(启动器)必须在**主线程**调用 <see cref="AvaloniaHost.RunOnCurrentThread"/>:
|
||||
/// macOS 的 AppKit 要求 NSApplication 运行在主线程,否则打开模型窗口时整个进程会崩溃。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port, out AvaloniaHost uiHost)
|
||||
{
|
||||
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
|
||||
var services = AppServices.Create();
|
||||
var uiHost = new AvaloniaHost(services);
|
||||
var host = new AvaloniaHost(services);
|
||||
uiHost = host;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||||
builder.Logging.ClearProviders();
|
||||
@@ -161,8 +175,8 @@ public static class BackendServer
|
||||
true,
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||
LauncherRuntimeInfo.CurrentRid,
|
||||
uiHost.IsAvailable,
|
||||
uiHost.LastError)));
|
||||
host.IsAvailable,
|
||||
host.LastError)));
|
||||
|
||||
// ---- 已安装模型 -----------------------------------------------------------
|
||||
|
||||
@@ -190,7 +204,7 @@ public static class BackendServer
|
||||
try
|
||||
{
|
||||
services.Memory.Refresh();
|
||||
var message = await uiHost.LaunchAsync(package);
|
||||
var message = await host.LaunchAsync(package);
|
||||
return Results.Ok(new LaunchResultDto(true, message));
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
using GC.UI.Server;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
// 独立进程入口:`GC.UI.Server --port 17890`
|
||||
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
|
||||
var app = BackendServer.StartFromCommandLine(args);
|
||||
app.Run();
|
||||
var app = BackendServer.StartFromCommandLine(args, out var host);
|
||||
|
||||
// 模型窗口由 Avalonia 承载,macOS 的 AppKit 要求 NSApplication 在主线程。
|
||||
// 所以后端交给 Kestrel 自己的线程池在后台跑,主线程留给 Avalonia 事件循环。
|
||||
app.StartAsync().GetAwaiter().GetResult();
|
||||
host.RunOnCurrentThread();
|
||||
|
||||
if (host.IsAvailable)
|
||||
{
|
||||
// 事件循环结束 → 收尾后端
|
||||
app.StopAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 无图形环境(无头调试):退化为纯后端常驻
|
||||
app.WaitForShutdown();
|
||||
}
|
||||
Reference in new issue
Block a user