Why does Code Analysis tell me, “Do not dispose objects multiple times” here:

后端 未结 2 2057
一生所求
一生所求 2020-12-21 12:17

On this code:

public static string Base64FromFileName(string fileName)
{
    try
    {
        FileInfo fInfo = new FileInfo(fileName);
        long numBytes         


        
2条回答
  •  离开以前
    2020-12-21 12:32

    Code Analysis is right; Code Analysis is wrong.

    Yes, you're closing the FileStream twice. This is harmless. So is disposing it twice. Multiple disposal happens. It is the responsibility of the developer of a disposable component to handle multiple disposal properly and without throwing exceptions1.

    However, while calling Dispose() on a disposed FileStream is a no-op by convention, the same isn't true of your code, which calls Close() on a disposed stream. Don't do that.

    Your suggested fix with the nested using is fine.


    1 The contract for IDisposable.Dispose requires:

    If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

    The formal term for this behavior is idempotence.

提交回复
热议问题