Skip to main content
 首页 » 编程设计

c#之AppDomain.CurrentDomain.ProcessExit 不执行 Console.WriteLine

2024年02月20日22pander-it

using System; 
using System.IO; 
using System.Runtime.Serialization.Formatters.Binary; 
 
namespace empty 
{ 
    class Program 
    { 
        static Program() 
        { 
            AppDomain.CurrentDomain.ProcessExit += ExitHandler; 
        } 
        static void Main(string[] args) 
        { 
        } 
        static void ExitHandler(object o, EventArgs args) 
        { 
            using (FileStream fs = new FileStream("file.bin", FileMode.Create)) 
            { 
                BinaryFormatter bf = new BinaryFormatter(); 
                bf.Serialize(fs, new double[30000000]);          
            } 
            using (FileStream fs = new FileStream("file.bin", FileMode.Create)) 
            { 
                BinaryFormatter bf = new BinaryFormatter(); 
                bf.Serialize(fs, new double[30000000]); 
            } 
            Console.WriteLine("end"); 
        } 
    } 
} 

我期望得到输出: “结尾” 但什么也得不到。我做错了什么?

我有意使用 2 个序列化,因为 1 个序列化不会发生这种行为。

请您参考如下方法:

如果你看the documentation for ProcessExit ,你会发现这个:

The total execution time of all ProcessExit event handlers is limited, just as the total execution time of all finalizers is limited at process shutdown. The default is two seconds.

因此,如果您在该处理程序中执行的任何操作花费的时间超过两秒,则它不会完全执行。这似乎正是您遇到的问题。