Quantcast
Channel: MetroStar Systems Blog » C#
Viewing all articles
Browse latest Browse all 11

C# Generator best practices

$
0
0

A while back C# introduced generators (through the use of yield return) which is a very handy/powerful construct if used properly.  However if your not careful there are a few gotchas which novice developers may not be aware of:

Resource Cleanup

If code inside of the generator is using any resources which need to be cleaned up / disposed of make sure to use a using statement or try/finally.  If for instance you have a generator method yield returning rows from a database make sure the SqlConnection (or whatever other connection it may be) is wrapped in a using to ensure that the connection is disposed of.  The following code demonstrates the issue of not making use of using or a try/finally:

In the above code the the generator is designed to return integers 0 – 999, however the foreach loop it is running within is broken out of after 10 loops which means the generator’s code stops running before the for loop exits.  If the code after the loop was to perform some sort of cleanup it would never execute leading to leaked connections / memory etc…

 

Lazy Evaluation

Since generators are effectively a form of lazy evaluation where data is not computed/returned until it is asked for there use can cause some problems if your aren’t careful.  The following code demonstrates this problem:

In the above code the SqlConnection being used inside of the generator is the same one being used inside of the foreach inside of the Main function.  Since the generator is lazily returning data inside of the foreach loop sqlConn is in the middle of an ongoing command when ‘SELECT * FROM OtherTable’ is attempting to be run.  This will generate an exception since the SqlConnection can only be used by a single SqlCommand at any given moment.

If your code requires something similar to this your two best options are going to be either creating a separate SqlConnection inside of the generator (using a using of course) or ‘sealing’ the data coming back from the generator using the LINQ IEnumerable.ToArray (or something similar) which forces the evaluation of the generator leaving sqlConn available for use in the foreach loop.

 

The post C# Generator best practices appeared first on MetroStar Systems Blog.


Viewing all articles
Browse latest Browse all 11

Trending Articles