Thursday, November 25, 2010

Exception in a Static Constructor

Some days ago, a coworker of mine had a very nasty bug which no one had a immediate explanation for: The problem was that in his application, he was trying to call a service: usually this worked just fine, but when the service was shut down while he started his tool, his application stopped working even tough the service was started right afterwards again.

After some research and debugging, he found the problem and since nobody in my team actually knew that, I think it's worth a post.

So what was he doing: He had a static class and in it's static constructor, the service was called.

public class MyClass
{
    static MyWebservice _ws;
    static Data _data;
    static MyClass()
    {
        _ws = new MyWebservice();
        _data = _ws.GetBasicDataWhichWontChange();
    }

    public MyClass()
    {
        //init
    }

    public void StoreSomeData(string someData)
    {
        //store it
    }
}

This class was used in a way, that he initialized it with the new keyword and wanted to call some methods like StoreSomeData in there.

MyClass myClass = new MyClass();
myClass.StoreSomeData("mydata");

Now, since the webservice was shut down before the initialization of his tool, this constructor threw an exception that the service was not there. This exception was handled accordingly but after turning on the service, the same exception about the unreachable webservice was thrown when calling some method of this class.

Why? The exception itself was only caused once (the service was not reachable) but because the static constructor is only called before the first use of the class (this should be clear), the exception which was thrown in this first init was saved and re-thrown every time the class was called.

It took quite some time to figure that out, so I hope to save somebody this effort.

Here is the according MSDN-Article.

1 comment:

  1. Pikachu Games : Play Free Online Pikachu Games. Pikachu games new version - HOT Pikachu Online Gamse world. Pikachu games on PC

    ReplyDelete