C#: “Using” Statements with HttpWebRequests/HttpWebResponses

前端 未结 3 356
时光说笑
时光说笑 2020-12-16 11:26

Jon Skeet made a comment (via Twitter) on my SOApiDotNet code (a .NET library for the pre-alpha Stack Overflow API):

@maximz2005 One thing I\'ve noticed

相关标签:
3条回答
  • 2020-12-16 12:09

    In order to prevent memory leaks you should call Dispose on every object that implements IDisposable. You can ensure that the Dispose method in called by using the using keyword (no pun intended) as it is just a syntactic sugar for try-finally block.

    0 讨论(0)
  • 2020-12-16 12:22

    Everything wrapped in a using () {} block (that is, inside of the first brackets) is disposed when you leave the scope.

    I haven't used your library so far (seems nice though), but I'd argue that you should explicitly dispose every IDisposable you create (= are responsible for) and don't return to a caller.

    A sidenote, since I've seen a lot of people struggling with multiple things to dispose: Instead of

    using (var foo = SomeIDisposable) {
      using (var bar = SomeOtherIDisposable) {
      }
    }
    

    which needs a lot of vertical space you can write

    using (var foo = SomeIDisposable)
    using (var bar = SomeOtherIDisposable) {
    }
    
    0 讨论(0)
  • 2020-12-16 12:30

    HttpWebRequest itself is not disposable unlike HttpWebResponse. You should wrap disposable resources with using to allow early and determined cleanup. Correctly implemented IDisposable pattern allows multiple calls to Dispose without any issues so even the outer using statement wraps resource that during its own dispose disposes inner using statement resource it is still ok.

    Code example

    var request = (HttpWebRequest)WebRequest.Create("example.com"); 
    using (var response = (HttpWebResponse)request.GetResponse()) 
    { 
        // Code here 
    }
    
    0 讨论(0)
提交回复
热议问题