开发者

When there are multi using statement, will they be execute in order?

开发者 https://www.devze.com 2023-01-26 11:21 出处:网络
for example using (Stream ftpStream = ftpResponse.GetRes开发者_如何学编程ponseStream())// a using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b

for example

  using (Stream ftpStream = ftpResponse.GetRes开发者_如何学编程ponseStream())       // a             
  using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b
  {
                 ........do something
  }

will the two statement a and b executed in the order i put? and displose in the same order as well??

Thanks


They will execute in textual order, and be disposed in reverse order - so localFileSream will be disposed first, then ftpStream.

Basically your code is equivalent to:

using (Stream ftpStream = ...)
{
    using (FileStream localFileStream = ...)
    {
        // localFileStream will be disposed when leaving this block
    }
    // ftpStream will be disposed when leaving this block
}

It goes further than that though. Your code is also equivalent (leaving aside the different type of localFileStream) to this:

using (Stream ftpStream = ..., localFileStream = ...)
{
    ...
}


Yes. This syntax is just a shortcut or alternative way of nesting using statements. All you're doing is omitting the brackets on the first using statement. It's equivalent to:

using (Stream ftpStream = ftpResponse.GetResponseStream())
{
    using (FileStream localFileStream = (new FileInfo(localFilePath)).Create())
    {
        //insert your code here
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消