标签:this arp finalize inter 范围 console nali 西班牙 sha
明明同事用了using来确保区块结束时会调用Dispose()作到自动释放资源,但还是被源码检测工具fortify举报。呼~~来解题。
如下,Developer都很乖有使用using定义对象范围来让using区块结束时调用Dispose()作到自动释放资源
using (FileStream fsInFile = new FileStream(@"C:Testfile.txt", FileMode.Open, FileAccess.Read, FileShare.None))
{
    using (StreamReader srInFile = new StreamReader(fsInFile, System.Text.Encoding.Default))
    {
        string strInfData;
        while ((strInfData = srInFile.ReadLine()) != null)
        {
            throw new Exception("somebody else"); //故意直接跳出method
        }
    }
}
另外,微软docs对于using陈述式的说明:
提供方便的语法,以确保正确使用 IDisposable 对象。
但被扫出Unreleased Resource: Streams

查了using在微软docs的说明,有一行吸引了眼球,文档她说即使发生Exception,也可以确保会执行Dispose
The?using?statement ensures that?Dispose?is called even if an exception occurs within the?using?block.
看来是fortify误判了。
老招,继续神鬼交锋,那我们在出事前加上一行Dispose()
using (FileStream fsInFile = new FileStream(@"C:Testfile.txt", FileMode.Open, FileAccess.Read, FileShare.None))
{
    using (StreamReader srInFile = new StreamReader(fsInFile, System.Text.Encoding.Default))
    {
        string strInfData;
        while ((strInfData = srInFile.ReadLine()) != null)
        {
            fsInFile.Dispose();
            throw new Exception("somebody else");
        }
    }
}
重新扫描:

结案!
除了看微软Docs文档,我们也科学的做实验。
我们有一个球员class:Footballer,New一个马竞前锋grizmann起来执行射门之后,我们故意进入Exception,看看解构函示是否会执行?
using System;
namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("程序开始");
            Attack();
            Console.WriteLine("程序结束");
        }
        private static void Attack()
        {
            using (Footballer griezmann = new Footballer())
            {
                try
                {
                    griezmann.Shot();
                    throw new Exception("Error");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return;
                }
            }
        }
    }
    internal class Footballer : IDisposable
    {
        public Footballer()
        {
            Console.WriteLine("建构函数");
        }
        public void Shot()
        {
            Console.WriteLine("射门!!!");
        }
        public void Dispose()
        {
            Console.WriteLine("解构函数");
            GC.SuppressFinalize(this);
        }
    }
}
有执行解构!资源会被释放~

Semi Finals

期待的4强,就少了西班牙。
微软docs using陈述式
https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/keywords/using-statement
原文:大专栏 [Fortify][.NET]Unreleased Resource: Streams 排除
[Fortify][.NET]Unreleased Resource: Streams 排除
标签:this arp finalize inter 范围 console nali 西班牙 sha
原文地址:https://www.cnblogs.com/petewell/p/11445416.html