基本上,这个问题也总结了我的问题: SystemEvents.SessionEnding not fired until a Process (opened before) gets closed
但目前还没有答案。我有一个控制台应用程序,从内部启动另一个进程。该应用程序还侦听SystemEvents.SessionSwitch。如果我注释掉启动附加进程的代码,则会触发SessionSwitch的事件处理程序。但是,如果我取消注释启动其他进程的代码,则不会命中处理程序。我100%确信事件处理程序没有被命中是因为我的应用程序内部启动了一个新进程......我只是不知道为什么。
我将此标记为可能的多线程问题,因为这是上面发布的问题中的一些评论似乎表明的。但是,我完全不确定是什么导致它。
这是一些代码。
[STAThread]
static void Main(string[] args)
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
_myFoo = new _myFoo();
_processManager = new ProcessManager();
// If I comment out this code block, the SessionSwitch event handler is hit
// ------------------------------------------------------
if (args.Length == 0)
{
// creates a duplicate process to monitor the current (main) process
_processManager.StartObserverProcess();
}
else
{
// start monitoring the main process
_processManager.ObserveMainProcess(int.Parse(args[0]));
}
// ----------------------------------------------------
_myFoo.Start();
}
// this method does not get hit if we start the 'duplicate'
// monitoring process from within ProcessManager
private static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
// Do something when session locked
}
if (e.Reason == SessionSwitchReason.SessionUnlock)
{
// Do something when session unlocked
}
}
ProcessManager基本上启动另一个“重复”进程,监视当前进程是否退出(我知道这里的术语“重复”可能不准确)。这是一段摘录:
public class ProcessManager
{
// create a new process to monitor the current process
// passing in the current process id as args
public void StartObserverProcess()
{
_mainProcess = Process.GetCurrentProcess();
_mainProcessId = _mainProcess.Id;
_observerProcess = new Process
{
StartInfo =
{
FileName = _mainProcess.MainModule.FileName,
Arguments = _mainProcessId.ToString()
},
EnableRaisingEvents = true
};
_observerProcess.Exited += OnObserverProcessExit;
_observerProcess.Start();
}
private void OnObserverProcessExit(object sender, EventArgs e)
{
// do something on main process exit
}
}