Fix Windows exit hang from wedged camera capture thread

- App: bounded host dispose then TerminateProcess on Windows exit
- LocalSettings: ForceSave writes synchronously before terminate
- DebounceFunction: add Cancel()
- VFT backend: only probe devices present in enumeration
This commit is contained in:
dan2wik committed 2026-06-26 10:46:23 +10:00
1 parent ffccb8c113
commit 76516a9890
4 files changed
+59 -3

No files matched your search

+19 -2
View File
@@ -237,8 +237,25 @@ public partial class App : Application
desktop.MainWindow.Loaded += (_, _) => { desktop.MainWindow.ShowOnboardingIfNeeded(); };
desktop.Exit += (s, e) =>
{
OnShutdown(s, e);
_host.Dispose();
OnShutdown(s, e); // flushes settings synchronously (ForceSave) + teardown
// On Windows the OpenCV/DirectShow camera capture wedges its native Read()/Release()
// during teardown, leaving a thread the OS can't reap; a graceful _host.Dispose()
// then waits on it forever, so the process lingers in the background after the window
// closes (you'd have to End Task it). Try a bounded graceful dispose, then
// force-terminate: TerminateProcess reaps the wedged camera thread that a cooperative
// exit (ExitProcess) cannot. Linux's V4L2/GStreamer capture unblocks cleanly, so it
// keeps the normal graceful path.
if (OperatingSystem.IsWindows())
{
Task.Run(() => { try { _host.Dispose(); } catch { /* ignore */ } })
.Wait(TimeSpan.FromSeconds(2));
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
else
{
_host.Dispose();
}
};
desktop.ShutdownRequested += OnShutdown;
break;
@@ -73,8 +73,17 @@ public class SingleCameraSourceFactory
// dependency-free "V4L2 Camera" one instead of failing outright.
private SingleCameraSource? StartWithFallback(string address, string camera, string providerName)
{
// The Vive Facial Tracker backend fires a native USB tracker-enable (enableViveFacialTracker)
// *before* it ever opens the camera. On a name that isn't a real, present tracker — e.g. a
// stale saved camera that has since been unplugged — that native call wedges a thread Windows
// can't reap, so the process lingers as a ghost after the window closes. Only offer VFT for a
// device the current enumeration actually knows about. Other backends open lazily and fail
// gracefully, so they don't need this guard. (Linux's VFT only matches /dev/video* paths, which
// don't exist when unplugged, so present setups there are unaffected.)
var deviceIsPresent = IsEnumeratedDevice(address) || IsEnumeratedDevice(camera);
var candidates = _platformConnector.GetCaptureFactories()
.Where(factory => factory.CanConnect(camera))
.Where(factory => deviceIsPresent || !IsViveFacialTracker(factory))
.ToList();
if (!string.IsNullOrEmpty(providerName))
@@ -142,4 +151,17 @@ public class SingleCameraSourceFactory
_logger.LogError("No data was received from {} on any backend, closing... Maybe the camera is opened somewhere else?", address);
return null;
}
// A device is "present" when the current enumeration knows it — either as a friendly-name key or
// as a resolved value (a camera index like "0", a "/dev/videoN" path, or a COM port). Used to keep
// the wedge-prone VFT backend off stale/absent device names.
private bool IsEnumeratedDevice(string address)
{
var cameras = _deviceEnumerator.Cameras;
return cameras != null && (cameras.ContainsKey(address) || cameras.Values.Contains(address));
}
// Matches VFTCaptureFactory.GetProviderName().
private static bool IsViveFacialTracker(ICaptureFactory factory) =>
string.Equals(factory.GetProviderName(), "Vive Facial Tracker", StringComparison.Ordinal);
}
@@ -27,4 +27,9 @@ public class DebounceFunction
_timer.Stop();
_action();
}
public void Cancel()
{
_timer.Stop();
}
}
@@ -99,7 +99,19 @@ public class LocalSettingsService : ILocalSettingsService
public void ForceSave()
{
_debouncedSave.Force();
// Synchronous by design: this runs during shutdown, just before the process is force-terminated
// (the camera teardown can wedge a native thread, so we don't get a clean exit to flush on).
// The debounced async writer wouldn't finish in time.
_debouncedSave.Cancel();
try
{
var json = JsonSerializer.Serialize(_settings, _jsonSerializerOptions);
File.WriteAllText(_localSettingsFile, json);
}
catch (Exception e)
{
_logger.LogError("Could not save settings file: {}", e);
}
}
public void SaveSetting<T>(string key, T value, bool forceLocal = false)