C#: “Using” Statements with HttpWebRequests/HttpWebResponses

前端 未结 3 357
时光说笑
时光说笑 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: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 
    }
    

提交回复
热议问题