Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to know which is the best way to use the 'using' block in C#.

Approach 1: Looping inside the 'using' block

void MyMethod(List<Prod> productList)
{
    using(MyResource mr = new MyResource())
    {
        foreach(Prod product in productList)
        {
            //Do something with the resource
        }
    }
}

Approach 2: Looping outside the 'using' block

void MyMethod(List<Prod> productList)
{
    foreach(Prod product in productList)
    {
        using(MyResource mr = new MyResource())
        {
        //Do something with the resource
        }
    }
}

I want to know which approach is preferable and why. Will there be performance differences between the two? Also how does it differ if the resource is... say a database connection or an object?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

In approach 1, you create your resource once for your loop.

In approach 2, you create a new resource on each Product in your product list.

Unless it is necessary the approach 2 is not recommended.

Approach 1 have a better performance, there are fever object created/destroyed (and memory consumed). Especially if it's a database, event if there are a pool connection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...