65.9K
CodeProject 正在变化。 阅读更多。
Home

“csc.exe – 应用程序错误” 在关闭运行中的 .NET 应用程序时

2023年5月7日

CPOL
viewsIcon

6245

修复“csc.exe – 应用程序错误”

最近,一位朋友向我报告说,我用 .NET 编写的应用程序阻止了他的计算机关机。如果应用程序在 Windows 尝试关机时正在运行,则会出现以下错误消息,并且 Windows 无法关机

csc.exe – Application Error

The application failed to initialize properly (0xc0000142). 
Click on OK to terminate the application.

一些调查显示,该问题与 .NET 类 XmlSerializer 有关。我的应用程序将用户数据存储到 XML 文件中,并在应用程序关闭时保存该文件。特别是,以下代码似乎导致了问题

Dim serializer As New XmlSerializer(ConfigObj.GetType())
Dim writer As New StreamWriter(datafile)
serializer.Serialize(writer, ConfigObj)
writer.Close()

错误在调用 XmlSerializer.Serialize() 时立即发生。文件系统监视工具(例如 Process Monitor)显示 csc.exeC:WindowsTemp 中创建临时文件,这可能被关机过程中断,从而导致上述问题。我甚至不确定为什么会调用 csc.exe(Microsoft C# 编译器),即使我使用的是 VB.NET!

不确定如何解决这个问题,我必须通过使用以下方法避免在 Windows 关机时调用 XmlSerializer

Private Sub Form1_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
…

If e.CloseReason <> CloseReason.WindowsShutDown 

   Dim serializer As New XmlSerializer(ConfigObj.GetType())
   Dim writer As New StreamWriter(datafile)
   serializer.Serialize(writer, ConfigObj)
   writer.Close()

End If
… 

End Sub

这样,用户数据可能会丢失,但至少我的应用程序不会阻止系统关机。我需要找到另一种更频繁地保存用户数据的方法…

参考

© . All rights reserved.