using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FastGithub.Windows.Hosting
{
///
/// WinForm后台任务和WinForm线程
///
///
sealed class WinFormHostedService : IHostedService where TMainForm : Form
{
private readonly Thread staThread;
private readonly IServiceProvider serviceProvider;
private readonly TaskCompletionSource taskCompletionSource = new();
///
/// WinForm后台任务
///
///
public WinFormHostedService(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
this.staThread = new Thread(StaRunMainFrom);
this.staThread.TrySetApartmentState(ApartmentState.STA);
}
///
/// 启动
///
///
///
public Task StartAsync(CancellationToken cancellationToken)
{
this.staThread.Start();
return this.taskCompletionSource.Task;
}
///
/// STA线程
///
private void StaRunMainFrom()
{
try
{
var mainForm = this.CreateMainForm();
this.taskCompletionSource.TrySetResult();
Application.Run(mainForm);
}
catch (Exception ex)
{
this.taskCompletionSource.TrySetException(ex);
}
}
///
/// 实例化MainForm与初始化调度器
///
///
private TMainForm CreateMainForm()
{
// 在STA线程实例化TMainForm,保证该线程拥有SynchronizationContext
var mainForm = this.serviceProvider.GetRequiredService();
if (SynchronizationContext.Current is null)
{
throw new InvalidOperationException($"不允许在其它线程上实例化{typeof(TMainForm)}");
}
var dispatcher = this.serviceProvider.GetRequiredService();
dispatcher.SynchronizationContext = SynchronizationContext.Current;
return mainForm;
}
///
/// 停止
///
///
///
public Task StopAsync(CancellationToken cancellationToken)
{
Application.Exit();
return Task.CompletedTask;
}
}
}