1

我正在尝试将日志文件添加到我正在制作的程序中,但是当我告诉主线程退出(使用Application.ExitThread())时,logstrmWriter它在到达那里之前突然为空。这是一个非常简单的脚本。

private static FileStream appLogStream;
internal static string logFile;
internal static StreamWriter logstrmWriter;
public static void Main()
{    
    logFile = Application.StartupPath + @"\Archiver.log";
    appLogStream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read);
    TextWriter logtxtWriter = Console.Out;
    StreamWriter logstrmWriter = new StreamWriter(appLogStream);
    if(!console) Console.SetOut(logstrmWriter);

    Application.ApplicationExit += new EventHandler(OnApplicationExit);
    Application.Run();
}
internal static void OnApplicationExit(object sender, EventArgs e)
{
    active = false; Console.WriteLine("Main thread is shutting down. Sending Interrupt...");
    Archiver.Stop(); Console.WriteLine("Shutdown. Log and Exit");
    Console.WriteLine();
    logstrmWriter.Flush();
    logstrmWriter.Close();
    logstrmWriter.Dispose();
}
4

1 回答 1

2

您正在创建一个隐藏相关静态变量的局部变量。因此,您根本不会初始化logstrmWriter

TextWriter logtxtWriter = Console.Out;
/* StreamWriter */ logstrmWriter = new StreamWriter(appLogStream);  // Remove the redeclaration here!
if(!console) Console.SetOut(logstrmWriter);
于 2012-06-05T23:42:25.387 回答