我写一个远程调用的程序,客户端是个Console程序,开始时会注册了远程调用类的一个事件,也就是可以实现当有指示信息时向客户端发送数据,所以在客户端退出时必须取消这个事件的注册,不然服务器还是会认为客户还在,当有这个客户的信息时还是会向它下发信息,这时就会出错!我找到一些代码是可以取得Console退出时的消息,在这时是可以加入取消事件注册的代码,但问题是Console程序是不会等这些代码执行完后再退出的!所以很多时这些代码是没有被执行到的!所以我想应该是要把Console程序关闭的信息给拦截掉,执行代码再退出,这样才行!!能否把Console程序关闭时的的信息给拦截掉呢???下面是取得Console程序退出时的事件,执行后可以看到它是不会等到执行完所有代码才退出的!
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;namespace 测试控制台关闭信息
{
public delegate bool ConsoleCtrlDelegate(int dwCtrlType);
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
//The SetConsoleCtrlHandler function adds or removes an application-defined HandlerRoutine function 
//from the list of handler functions for the calling process.
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine,bool Add);
//一個Ctrl + C的信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent 函數
private const int CTRL_C_EVENT = 0;
//一個 Ctrl + Break 信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent 函數
private const int CTRL_BREAK_EVENT = 1;
//當用戶系統關閉Console時,系統會發送此信號到此
private const int CTRL_CLOSE_EVENT = 2;
//當用戶退出系統時系統會發送這個信號給所有的Console程序。該信號不能顯示是哪個用戶退出。
private const int CTRL_LOGOFF_EVENT = 5;
//當系統將要關閉時會發送此信號到所有Console程序
private const int CTRL_SHUTDOWN_EVENT = 6;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Class1 cl=new Class1();
} public Class1()
{
ConsoleCtrlDelegate newDategate=new ConsoleCtrlDelegate(HandlerRoutine);
bool re=SetConsoleCtrlHandler(newDategate,true);
if(re)
{
Console.WriteLine("Set SetConsoleCtrlHandler success!!");
}
else
{
Debug.WriteLine("Set SetConsoleCtrlHandler Error!!");
}
Console.ReadLine();
} bool HandlerRoutine(int CtrlType)
{
switch(CtrlType)
{
case CTRL_CLOSE_EVENT:
for(int i=0;i<100;i++)
{
Console.WriteLine("i is:{0}",i);
Thread.Sleep(1000);
}
break;
}
return false;
}
}
}