Files
Febe/tests/Febe.Tests.Windows/Support/UiThread.cs
T
Alby96andClaude Opus 5.5 a25f60970d Prove per Windows con WebView2 vero, e la prova che riproduce l'avvio mancato
Nuovo progetto tests/Febe.Tests.Windows (net10.0-windows, WPF, solo MSTest e riferimenti ai
progetti): un thread STA con un Dispatcher di WPF vero, come il thread dell'interfaccia di
Febe.exe, e il browser di Febe costruito come lo costruisce la composizione e avviato da un
thread del pool, come fa FebeApp. Si compila anche da Linux (EnableWindowsTargeting, come
Febe.Desktop) perché la CI compila tutta la soluzione, ma gira solo su Windows; dove manca il
runtime WebView2 le prove risultano inconcludenti.

La prima prova riproduce il registro di Alberto del 14 e del 19 ottobre: «WebView2 non parte
(InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI
thread.)» a ogni tentativo. Con il codice di questo commit fallisce così; la correzione è nel
commit seguente.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:09:30 +02:00

56 lines
1.9 KiB
C#

using System.Windows.Threading;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// A UI thread like the one of Febe.exe: an STA thread running a WPF <see cref="System.Windows.Threading.Dispatcher"/>
/// (its message pump and its <see cref="DispatcherSynchronizationContext"/>). The browser of Febe is created on it,
/// while the test itself — like the engine of Febe — runs on thread-pool threads.
/// </summary>
internal sealed class UiThread : IAsyncDisposable
{
private readonly Thread _thread;
private UiThread(Thread thread, Dispatcher dispatcher)
{
_thread = thread;
Dispatcher = dispatcher;
}
public Dispatcher Dispatcher { get; }
/// <summary>The managed id of the UI thread (to tell where code ran).</summary>
public int ThreadId => _thread.ManagedThreadId;
public static async Task<UiThread> StartAsync()
{
var ready = new TaskCompletionSource<Dispatcher>(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
ready.SetResult(Dispatcher.CurrentDispatcher);
Dispatcher.Run();
})
{
IsBackground = true,
Name = "Febe: thread dell'interfaccia (prove)",
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
var dispatcher = await ready.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
return new UiThread(thread, dispatcher);
}
/// <summary>Runs <paramref name="action"/> on the UI thread and waits for it.</summary>
public Task<T> InvokeAsync<T>(Func<T> action) => Dispatcher.InvokeAsync(action).Task;
public async ValueTask DisposeAsync()
{
if (!Dispatcher.HasShutdownStarted)
{
Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
}
await Task.Run(() => _thread.Join(TimeSpan.FromSeconds(15))).ConfigureAwait(false);
}
}