2012-06-05 51 views
1

我正在嘗試向我正在創建的程序添加日誌文件,但是當我告訴主線程退出時(使用Application.ExitThread()),logstrmWriter在它到達之前突然變爲空。這是一個非常簡單的腳本。Stream Writer在程序退出前爲空

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(); 
} 

回答

2

您正在創建隱藏所討論的靜態變量的局部變量。因此,你永遠不會初始化logstrmWriter

TextWriter logtxtWriter = Console.Out; 
/* StreamWriter */ logstrmWriter = new StreamWriter(appLogStream); // Remove the redeclaration here! 
if(!console) Console.SetOut(logstrmWriter);