Archive for January, 2011

Multithreaded Programming in .Net with C# – Aggregated Exceptions


Introduction

This may seem like an odd topic for inclusion in my multithreaded in C#, with the .Net 4.0 framework. If you read on you will see why this is  a topic for consideration when programming using the .Net 4.0 Framework. When you see why the designers of the .Net Framework included the AggregateException Class you will see that there is a use case here which needed to be addressed.

Background

My previous blog post in this series was: Parallel Programming in .Net – Resources.

The Prompt For this Blog Post

Another resource:   Aggregating Exceptions or http://msdn.microsoft.com/en-au/magazine/ee321571.aspx

This is an interesting article on the AggregateException Class. This class is heavily used in the .Net Framework parallel support classes. Why? Read on for some explanations as to why the .Net Framework needed aggregated exceptions.

Single Threaded Exception Model

In single the single threaded programming model, one thread can only throw one exception at a time.

The following is a very simple example of exception processing in a single threaded environment. What it does show is that only one exception can be “active” at once.

private void method_a()
{
    try
    {
        method_b();
    }
    catch (NotImplementedException ex)
    {
        Debug.WriteLine(ex);
    }
}

private void method_b()
{
    throw new NotImplementedException();
}

Multiple Threaded Exception Model

In the multiple threading model you can potentially have multiple exceptions being thrown (one from each thread executing).

The following is a very simple example. There are a couple of point to note:

  • I don’t know how many exceptions will be thrown.
  • The number of exceptions depends on a number of factors wedged into the Parallel.For method.
    • How many CPU’s (or hardware threads) the machine has. The implementation scales out to what the machine has.
    • The implementation could called from another Parallel.For (or any other Framework Parallel method – including Parallel LINQ), so again the number of threads available is unknown.
    • The implementation has it’s own scale across algorithms. So again depending on the way the algorithm reacts to the current workload, we could get any number of threads.
private void root_Method()
{
    Parallel.For(1, 20, a=> {
        throw new NotImplementedException(a.ToString());
    });
}

There are a number of things which should be made clear. These are:

  1. We don’t know how many exceptions the caller should get.
  2. The ordinary exception cannot cater for more than one “meaning”. The Exception Class has an (just one) inner exception only.
  3. How does the implementation of Parallel.For decide which exception it should pass back from an arbitrary delegate (or, any code you like).

Why We Need Aggregated Exceptions?

The above starts to outline the use case for an aggregated exception, or more to the point an exception which can contain multiple exceptions. When you have multiple threads of execution each of those threads could throw an exception. These exceptions should go back to the thread which propagated the multiple threads. The caller should be “told” about all of the problems which occurred. As a result the .Net Framework “packs” all of these exceptions which occurred in the parallel operations into one exception which is passed (thrown) back to the caller. Acting as a container for all exceptions generated in a function is the function which the AggregateException Class performs.

The Structure of the AggregateException Class Class

The following code snippet is lifted from the MSDN article Aggregating Exceptions. I have included the code here so that I can highlight some of the additions that the AggregateException Class has, when compared to the “normal” exception classes.

[Serializable]
[DebuggerDisplay("Count = {InnerExceptions.Count}")]
public class AggregateException : Exception
{
    public AggregateException();
    public AggregateException(params Exception[] innerExceptions);
    public AggregateException(IEnumerable<Exception> innerExceptions);
    public AggregateException(string message);
    public AggregateException(string message, Exception innerException);
    public AggregateException(string message,
        params Exception[] innerExceptions);
    public AggregateException(string message,
        IEnumerable<Exception> innerExceptions);

    public AggregateException Flatten();
    public void Handle(Func<Exception, bool> predicate);

    public ReadOnlyCollection<Exception> InnerExceptions { get; }
}

AggregateException.InnerExceptions Propertyimage

This is where the exceptions from the multiple threads are stored. There is a subtle nuance in this storage structure, which is that it is a hierarchical representation of the exceptions thrown.

The following diagram attempts to show that one AggregatedException can contain other Aggregated Exceptions, and ordinary exceptions. The .Net Framework will generate another “level” (insert another aggregated exception) when there is another level of the parallel support in the Framework is invoked. For example, a Parallel.For which invokes a child Parallel.For. These parent child relationships are preserved in the aggregated exception structure which the Framework generates.

AggregateException Constructor

It is worth noting that the constructors for the AggregatedException include the ability to construct an AggregatedException from collections of exceptions. As you would expect, when building a container object.

AggregateException.Flatten Method

This is an interesting method which has been included into the implementation of the AggregatedException. It simply flattens the hierarchal, or nested, structure which the AggregatedException contains into a single level representation. This representation is then ideal for applying LINQ to the inner exceptions collection, and “pulling” out the exceptions you are interested in.

The following is a non functional piece of code, but demonstrates the use of the Flatten method with LINQ.

AggregateException sample = new AggregateException();
var interesting_exceptions = from ex in sample.Flatten().InnerExceptions
                             where ex is DivideByZeroException
                             select ex;

AggregateException.Handle Method

The handle method is another way of working with the AggregatedException an the collection of exceptions which it can contain. This method produces an aggregated exception which contains just the exceptions which do not satisfy the predicate supplied.

try
{
    sample.Flatten().Handle(e => e is DivideByZeroException);
}
catch (AggregateException ex)
{
    // Sample minus the DivideByZeroExceptions
    Debug.WriteLine(ex);
}

Conclusions

I hope that this discussion of the AggregateException Class proves useful.

It is a part of the .Net 4.0 Framework which undoubtable any developer producing multithreaded code will need to deal with.

, , , , , , , , ,

Leave a comment

Using The Text Box in Word


Introduction

I have been writing an “Issues and Discussion Paper” at work, for the last week. This has meant I have spent a lot of time working in Word, mainly the outline view.

In drafting the paper I needed to inject some text from some preceding document into the report. To achieve a “neat” presentation for the quoted text, I decided to use the Text Box object. Well, this is where the “fun” (fun only if you are a masochist) started.

Why I use the Outline View

The outline feature of Word is something which I find invaluable. The outline feature of work is invaluable for structuring reports (in my opinion). The ability to start out with a broad outline, refine it by adding new elements, within the document’s hierarchy is invaluable. The other part of the outline which I use frequently is the ability to shuffle part of the document, picking up the heading, and all of the body text below it.

Sometime soon I post on this blog how to get the outline hierarchical numbering working as well. This is not simple to get working, but if you know how does a very good job of showing the structure of the document.

Where is the Text Box in Word?image

The following is the Word ribbon with the Insert tab selected. The Text Box is then last option shown in the image, there are other things after it, so don’t think it is the last thing on the list.

“Fun” With the Text Box

Why did I have “fun” with the Text Box? there are a couple of “features” which this object possesses which make it difficult to master. These include:image

  • The text box does not show up in the outline view. Not a big problem, but indicative of the fact that these are “graphical” objects which are being “massaged” into the text of a Word document.
  • These are graphical object. This means that they come with an anchor symbol (see the graphic). You may need to set the Word Options to see all of the characters (which will then show the anchor, and the paragraph mark)

I had the text boxes in my document “dancing” all over the place. In the print layout view, they could turn up on one page, or all on another page, or disappear altogether. This “behaviour” was exacerbated when I put more text into the document, above where the text boxes where (or should have been) located.

How I “fixed” the problemimage

The way I managed to get the text boxes staying where I wanted them, rather than were they wander to wander to, was to insert page breaks into the document. This effectively “nailed” each text box, and the associated text onto the one page. This stopped the text boxes wandering off.

The “Page Break” is located on the Insert tab of the Word ribbon.

Conclusion

Text boxes in Word are useful. Having developed this “trick” for keeping them “tied down” to a page, I think that I will use them more often in the “stuff” I write.

I hope this saves someone else, the “aggravation” of having these little things going for a wander in your Word document.

, , , , , , ,

4 Comments

Installing the Music Software on the New Machine


Introduction

This is a continuation of the previous post, Setting Up The New Machine, and concludes the installation of the music software, and device drivers for my music hardware. The music software is a qualified completion, I suspect that I’ll be learning what I really need, and loading add-on’s  for some time to come.

The installation of the device drivers for the music hardware was a smooth process. There were no “hiccups” in that process. The installation of Sonar and Guitar Tracks Pro is was a mostly painless process. There were a couple of notable low lights though.

Windows Upgrade

After making the point in my previous bog post that Windows Update can introduce consequential update dependencies. I forgot my wise advice. Upgrade to Windows Ultimate did leave a number of Windows Updates which needed applying, and those updates did need to be applied from multiple invocations of Windows Update. That’s right update A installed some “stuff”, and then that “stuff” also had updates. The chain of consequential updates resulted in the need for subsequent invocations of Windows Update to get all of the elements of the Windows OS up to date.

Guitar Pro Installing

This did cause some issues. Let me hasten to say that most of the issues were with Guitar Rig 3, rather than Guitar Pro. There is a side issue with Guitar Pro, which is that Guitar Rig only installs from the Guitar Pro Install, rather than “landing” somewhere where you can install, or reinstall, Guitar Rig. I could have “peered under the covers” and located the install for Guitar Rig, but it was getting late into the night, and rerunning the install was simpler.

Guitar Rig Issue

This is an issue I struck with the licence number part of Guitar Rig. If I applied my licence number straight after installing Guitar Pro, Guitar Rig would start in “demo mode”, seem to not recognise the licence number, even though the “Service Centre” acknowledges that the licence number has been applied.

Guitar Rig Solution

The way that I found to solve the problem, was to restart the machine after installing Guitar Pro, and Guitar Rig as part of the install. Then after the machine has rebooted, I applied the licence number. This “solved” the problem, and my copy of Guitar Rig was licenced, and Guitar Rig not started in normal mode, rather than “demo” mode.

Windows has a “bad habit” of keeping some system changes in a “pending pile” until the machine is restarted cleanly (not a crash restart). You see this sometimes with the “installing things x % done, please do not turn off the machine” massage when you shut down a machine. I guess, or suspicion points to, that something in Guitar Rig was in the windows “pending pile” until the machine was restarted.

The Sonar X1 Install

This one went smoothly as well.

There is a question early on in the install asking if you want the 32 or 64 bit version. I’ve opted for the 64 bit version. I’ve no idea whether this will prove to be the “wisest” choice. I guess that I’ll find out as I learn how to do things with Sonar.

Conclusion

The end of the process on a late night was a welcome relief. All seems to be up and running OK.

I now start crawling up the Sonar  learning curve. These thing are “big” pieces of software. Finding ones way around, and learning how to do the things I want to do will not be a simple process. A 1800+ page Reference Guide gives some idea of the size of the product.

, , , , , , ,

Leave a comment

%d bloggers like this: