c# – 我可以清除使用块内的外部变量吗?

我有一个静态StreamWriter字段用于我需要通过lambda函数访问的日志文件,该函数在长时间运行的Process上侦听StandardOutput.

我正在使用该字段的null / not-null状态来确定进程是否正忙于另一个线程;需要按顺序执行操作.

我的问题是,当我在使用块中将变量设置为null时会发生什么?它还能妥善处理吗?

public class Service
{
    private static StreamWriter logger;

    void Run(string logFile)
    {
        using (logger = new StreamWriter(logFile))
        {
            /* ... */

            logger = null;
        }
    }
}
最佳答案
根据C#参考,第8.13节,您的代码:

private static StreamWriter logger;

using (logger = new StreamWriter(logFile))
{
   /* ... */
   logger = null;
}

相当于

private static StreamWriter logger;


{  // using scope
   logger = new StreamWriter(logFile);
   IDisposable resource = logger;       // hidden var inserted by the compiler 
   try
   {
     /* ... */
     logger = null;
   }
   finally
   {
      if (resource != null)  
        resource.Dispose();
   }
}

相关报价:

A using statement of the form

    using (expression) statement

has the same three possible expansions, but in this case ResourceType is implicitly the compile-time type of the expression, and the resource variable is inaccessible in, and invisible to, the embedded statement.

转载注明原文:c# – 我可以清除使用块内的外部变量吗? - 代码日志