using System.Windows.Threading;
namespace Febe.Tests.Windows.Support;
///
/// A UI thread like the one of Febe.exe: an STA thread running a WPF
/// (its message pump and its ). The browser of Febe is created on it,
/// while the test itself — like the engine of Febe — runs on thread-pool threads.
///
internal sealed class UiThread : IAsyncDisposable
{
private readonly Thread _thread;
private UiThread(Thread thread, Dispatcher dispatcher)
{
_thread = thread;
Dispatcher = dispatcher;
}
public Dispatcher Dispatcher { get; }
/// The managed id of the UI thread (to tell where code ran).
public int ThreadId => _thread.ManagedThreadId;
public static async Task StartAsync()
{
var ready = new TaskCompletionSource(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);
}
/// Runs on the UI thread and waits for it.
public Task InvokeAsync(Func 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);
}
}