Skip to main content
 首页 » 编程设计

c#之为什么我的文本文件会突然停止保存

2024年02月13日11think

在这里受到聪明人的轻微批评,我将对 MessageBox.Show() 的调用切换为向 StringBuilder 写入行,后者随后保存到文件中,均来自应用程序的自定义异常处理程序:

public static void ExceptionHandler(Exception ex, string location) 
{ 
    try 
    { 
        if (inDebugMode) 
        { 
            LogMsgs.Append(string.Format("{0}\r\n", ex.Message));  
            DateTime dt = DateTime.Now; 
            string timeAsStr = string.Format("{0}_{1}_{2}_{3}.txt", dt.Hour, dt.Minute, dt.Second, dt.Millisecond); 
            using (StreamWriter file = new StreamWriter(timeAsStr)) 
            { 
                // If the app crashes, this is how the file is written; if it doesn't, it's written 
                // in frmCentral.Form1_Closing() 
                file.WriteLine(LogMsgs.ToString()); 
            } 
        } 
        MessageBox.Show("Exception: " + ex.Message + "\n\nLocation: " + location, GetFormTitle("CCR: " + ex.GetType().FullName,"","")); 
    } 

(...这样调用:

catch (Exception ex ) 
{ 
    CCR.ExceptionHandler(ex, "WriteXML.WriteFile"); 
    . . . 

) ...以及来自主窗体的 Closed() 事件:

private void frmCentral_Closed(object sender, EventArgs e) 
{ 
    if (CCR.inDebugMode) 
    { 
        DateTime dt = DateTime.Now; 
        string timeAsStr = string.Format("{0}_{1}_{2}_{3}.txt", dt.Hour, dt.Minute, dt.Second, dt.Millisecond); 
        using (StreamWriter file = new StreamWriter(timeAsStr)) 
        { 
            // If the app closes normally, this is how the file is written; if it doesn't,  
            // (it crashed) it's written in PDAClient.ExceptionHandler() 
            file.WriteLine(CCR.LogMsgs.ToString()); 
        } 
    } 
} // frmCentral_Closed 

直到今天早些时候,这还算正常。我没有更改该代码。但是现在,无论代码是否崩溃(我可以从主窗体中关闭它),文件都没有被写入(至少没有写入之前写入的位置,即手持设备的根目录)。

我正在添加类似的消息:

CCR.LogMsgs.Append(string.Format("DBCommand exception: {0}\r\n", ex.Message)); 

..并且 inDebugMode bool 值确实被设置为 true 而无处为 false:

public static bool inDebugMode = true; //TODO: Change this to false before deploying. 

是什么导致了这种恶意遗漏?

更新

回答 jp2code:

这是 ExceptionHandler 在其 catch block 中所做的:

catch(Exception exc) 
{ 
    MessageBox.Show("Exception Handler generated an exception!\n" + exc.Message + "\n\nCalling Location: " + location, GetFormTitle("CCR: " + exc.GetType().FullName,"","")); 
} 

请注意,我没有编写此代码,因此我经常(通常?)不知道大部分代码背后的动机或思维方式。对我来说,这似乎比 Italienfest 更像意大利面,但也许我只是不喜欢它。

很多东西都不是它们在代码中出现的样子,例如,void 函数被命名为好像它们是 bool 函数,而这个 ExceptionHandler() 方法你会认为(我会,无论如何),它是一个全局的/catch-all 异常处理程序,但实际上它必须在整个代码中从 catch block 显式调用才能执行。

此外:我尝试实现 errHndlrLock 代码,但得到编译错误消息,“非静态字段、方法或属性‘PDAClient.SSCS.errHndlrLock’需要对象引用”

更新 2

今天它恢复工作了;一定是内存问题或类似问题 - 尽管我昨天确实执行了热启动,没有喘息的机会。所以:它起作用了,突然失效了,然后突然(一夜之间)又开始起作用了。

更新 3

我认为这是一个关于调试日志文本文件神秘消失事件的线索。当我今天打开最新的时,它们塞满了:

StackOverflowException 
StackOverflowException 
StackOverflowException 
StackOverflowException 
StackOverflowException 
StackOverflowException 
StackOverflowException 

...这些已经够多了,我想整个 shebang 都决定去度假了。不过,现在它又一次停摆了——这种 CE 爵士乐比我祖母的馅饼皮还脆。

请您参考如下方法:

Nat 可以通过 Flush 调用来解决问题。我对此给了他 +1。

可能发生的另一件事(我遇到过)是多个项目试图同时访问您的异常处理程序。

假设您正在关闭表单,并且在您的方法之一中捕获了异常。现在您有两 (2) 个例程试图同时访问您的 timeAsStr 文件,这是不可能发生的。

一个解决方案是在您的异常处理例程中添加一个锁:

private object errHndlrLock = new Object(); 
 
public void ExceptionHandler(Exception ex, string location) { 
  lock (errHndlrLock) { 
    // continue with your code 
  } 
} 

我想到的另一件事:我看到您的异常处理程序代码显示了 try/catch block 的一部分。

问。您如何处理捕获到的异常?

如果您递归调用相同的方法,这可能会导致您丢失信息。

如果你想采用不同的方法,你可以使用一个Queue,定义为类的全局,以及你的StreamWriter:

class CCR { 
 
  private Queue<string> m_queue; 
  private StreamWriter m_writer; 
 
  public CCR() { 
    m_queue = new Queue<string>(); 
    m_writer = new StreamWriter(string.Format("Log_{0}.txt", DateTime.Now.ToFileTime())); 
  } 
 
  public void ExceptionHandler(Exception ex, string location) { 
    string item = string.Format("{0:u}: {1}\r\n\t\t{2}", DateTime.Now, location, ex.Message); 
    if (ex.InnerException == null) { 
      m_queue.Enqueue(item); 
    } else { 
      m_queue.Enqueue(item + string.Format("\r\n\t\tInner Exception: {0}", ex.InnerException.Message)); 
    } 
    QueueHandler(); 
  } 
 
  private void QueueHandler() { 
    while (0 < m_queue.Count) { 
      m_writer.WriteLine(m_queue.Dequeue()); 
    } 
  } 
 
  public void Close() { 
    QueueHandler(); 
    m_writer.Flush(); 
    m_writer.Close(); 
    m_writer.Dispose(); 
  } 

只需确保在代码退出之前调用 Close()