Try/Finally block vs calling dispose?

前端 未结 6 1158
栀梦
栀梦 2020-12-15 11:04

Is there any difference between these two code samples and if not, why does using exist?

StreamWriter writer;
try {
    writer = new StreamWrite         


        
6条回答
  •  我在风中等你
    2020-12-15 11:46

    There're some issues with your code. Never write like this (put using instead), and that's why:

    StreamWriter writer;
    try {
        // What if you failed here to create StreamWriter? 
        // E.g. you haven't got permissions, the path is wrong etc. 
        // In this case "writer" will point to trash and
        // The "finally" section will be executed
        writer = new StreamWriter(...) 
        writer.blahblah();
    } finally {
        // If you failed to execute the StreamWriter's constructor
        // "writer" points to trash and you'll probably crash with Access Violation
        // Moreover, this Access Violation will be an unstable error!
        writer.Dispose(); 
    }
    

    When you put "using" like that

      using (StreamWriter writer = new StreamWriter(...)) {
        writer.blahblah();
      }
    

    It's equal to the code

    StreamWriter writer = null; // <- pay attention to the assignment
    
    try {
      writer = new StreamWriter(...) 
      writer.blahblah();
    }
    finally {
      if (!Object.ReferenceEquals(null, writer)) // <- ... And to the check
        writer.Dispose();
    }
    

提交回复
热议问题