我编写了一个 WPF 应用程序,它在后台进行一些处理。当应用程序关闭时,我想等到处理完成后再停止处理。当我通过关闭表单关闭应用程序时,此代码运行完美。但是,当我将应用程序打开并从 Windows 会话中注销或重新启动机器时,应用程序似乎在 SemaphoreSlim.Wait() 上终止。奇怪的是事件日志中没有记录错误。我尝试使用 try catch 捕获错误,但仍然没有捕获错误。
这是我的代码:
public partial class NotifyWindow : Window
{
StreamWriter _stream;
public NotifyWindow()
{
InitializeComponent();
_stream = File.AppendText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt"));
WriteLine("startup");
}
private void WriteLine(string line)
{
var text = string.Format("{0} {1}", DateTime.Now, line);
lock (_stream)
{
_stream.WriteLine(text);
_stream.Flush();
}
}
SemaphoreSlim _locker = new SemaphoreSlim(0);
private void CloseMe()
{
WriteLine(string.Format("CloseMe started"));
Thread.Sleep(1000);
WriteLine(string.Format("release lock"));
_locker.Release();
WriteLine(string.Format("CloseMe finished"));
}
protected override void OnClosing(CancelEventArgs e)
{
WriteLine(string.Format("OnClosing started"));
base.OnClosing(e);
var t = new Thread(CloseMe);
t.Start();
WriteLine("Waiting on lock.");
_locker.Wait();
WriteLine("Waiting on lock finished.");
WriteLine(string.Format("OnClosing finished"));
}
}
这导致以下日志
When application is closed by closing the window
24-4-2017 13:57:29 startup
24-4-2017 13:57:30 OnClosing started
24-4-2017 13:57:30 Waiting on lock.
24-4-2017 13:57:30 CloseMe started
24-4-2017 13:57:31 release lock
24-4-2017 13:57:31 CloseMe finished
24-4-2017 13:57:31 Waiting on lock finished.
24-4-2017 13:57:31 OnClosing finished
When application is closed by windows logoff
24-4-2017 13:57:43 startup
24-4-2017 13:57:47 OnClosing started
24-4-2017 13:57:47 Waiting on lock.
24-4-2017 13:57:47 CloseMe started
有没有办法在关闭应用程序之前等待线程上的代码完成?我尝试了各种(如何等待线程完成.NET?)线程等待替代方案,但似乎都表现出相同的行为。
我正在使用 .net 4.6.2,并在 Windows 7 和 Windows 10 上重现了该问题。
TIA,
巴特弗里斯