Databases Reference
In-Depth Information
Figure 9-8 shows the sample application screen that creates the array of names to load in the shard. Six names are
added in the shard using round-robin, as previously described.
Figure 9-8. Sample application adding records using round-robin
Managing a Shard
Having created a shard and reached the point of being able to run queries and add data, you can begin to think about
higher-level issues: how to handle exceptions, manage performance, control transactions, and more.
Managing Exceptions
So far, you've learned the basic principles of the sample shard library. You saw how to select, insert, update, and delete
records in various ways through the methods provided by the library. Let's discuss how you can manage exceptions
that the shard may throw at you.
The current library doesn't handle rollbacks, but it may throw exceptions that your code needs to capture. In
the previous example (Figure 9-8 ), all the records were inserted except Jim Nastic: that name was too long for the
SqlParameter object (hence it threw a “Value Would Be Truncated” exception).
The library handles exceptions through the AggregateException class provided by the TPL; this class holds a
collection of exceptions. This is necessary because the library executes database calls in parallel. As a result, more
than one exception may be taking place at the same time. You need to aggregate these exceptions and return them to
the client for further processing.
For example, the shard library's ExecuteSingleNonQuery method takes a ConcurrentQueue<Exception>
parameter, which represents an object that stores exceptions. This object is thread-safe, meaning that all running
threads can add new exceptions to it safely without running into concurrency issues. The following code shows that if
an exception is detected in the ExecuteSingleNonQuery method, the code adds the exception to the queue on line 14.
Also, as a convention, the exception is rethrown if the queue isn't provided (line 16):
1. private static long ExecuteSingleNonQuery(
2. SqlCommand command,
3. SqlConnection connectionToUse,
4. System.Collections.Concurrent.ConcurrentQueue<Exception> exceptions
 
Search WWH ::




Custom Search