Sometimes, we need to perform some processing at the end of the program, such as logging logs and clearing some temporary files. At this time, we can use the processexit event of appdomain:
Class Program
{
Static void main (string [] ARGs)
{
Appdomain. currentdomain. processexit ++ = (sender, ARG) =>
File. writealltext (@ "C: \ log.txt", (appdomain) sender). friendlyname );
}
}
When the program runs, A log.txt file will be created on the C drive, and the specified information will be written. Generally, the sender in the parameter is the instance of the class to which the event belongs.
It is worth noting that the above exit event will not be executed when the program suffers an exception interruption. At this time, we can use the appdomain's unhandledexception event:
Class Program
{
Static void main (string [] ARGs)
{
Appdomain. currentdomain. unhandledexception + = (sender, ARG) =>
File. writealltext (@ "C: \ log.txt", (exception) Arg. exceptionobject). stacktrace );
Throw new exception ("Err !! ");
}
}
In combination with the use of these two events, we can establish a sound monitoring mechanism for the program, no longer have to worry about finding exceptions, or worry about missing log information records due to errors.
From: http://hi.baidu.com/expertsearch/blog/item/25bcd81197487806203f2e6b.html