3

Hope someone helps me with this

If CallbackHandler.proxy is static, then everything works fine:

using System;
using System.ServiceModel;

namespace ConsoleApplication5
{
    // Define class which implements callback interface of duplex contract
    public class CallbackHandler : ServiceReference1.IStockServiceCallback
    {
        public static InstanceContext site = new InstanceContext(new CallbackHandler());
        public static ServiceReference1.StockServiceClient proxy = new ServiceReference1.StockServiceClient(site);

        //  called from the service
        public void PriceUpdate(string ticker, double price)
        {
        }  
    }

    class Program
    {
        static void Main(string[] args)
        {
            CallbackHandler cbh = new CallbackHandler();
        }
    }
}

But if I declare it as an instance member, then I get System.TypeInitializationException: The type initializer for CallBackHandler’ threw an exception. ---> System.ArgumentNullException. Value cannot be null exception

using System;
using System.ServiceModel;

namespace ConsoleApplication5
{
    // Define class which implements callback interface of duplex contract
    public class CallbackHandler : ServiceReference1.IStockServiceCallback
    {
        public static InstanceContext site = new InstanceContext(new CallbackHandler());
        public ServiceReference1.StockServiceClient proxy = new ServiceReference1.StockServiceClient(site);

        //  called from the service
        public void PriceUpdate(string ticker, double price)
        {
        }  
    }

    class Program
    {
        static void Main(string[] args)
        {
            CallbackHandler cbh = new CallbackHandler();
        }
    }
}

Any idea why making CallbackHandler.proxy an instance member throws an exception?

EDIT:

In the 2nd case, the instance constructor in the line marked (*) runs before the completion of the static constructor (yes, it's possible), but at that point site is still not assigned.

Thus in second case site should be initialized to null, while in first case it should be assigned a non-null value?!

But…

At first I thought static site was null ( regardless of whether proxy was instance or static member ) simply because it was initialized with CallbackHandler, as explained here:

So when CLR tries to instantiate an instance O ( which it would then assign to site ), it waits for static field site to get initialized, while site waits for O to get created, which in turn would initialize site field. Since this could create a deadlock of sort, site is “the wiser” and thus gets set to default value null?!

Then I remembered that site is not null if proxy is also static, so my understanding of what’s happening changed to:

So when CLR tries to instantiate an instance O ( which it would then assign to site ), it waits for static field site to get initialized ( so that it can assign site’s reference to its instance member proxy ). while site waits for O to get created, which in turn would initialize site field. Since this could create a deadlock of sort, CLR detects this potential deadlock and sets site to null.

But then I’ve run your test code and for some reason site is assigned ( thus is not null ) even if proxy is not static:

using System;

namespace ConsoleApplication5
{
    public class InstanceContext
    {
        public InstanceContext(CallbackHandler ch)
        {
            Console.WriteLine("new InstanceContext(" + ch + ")");
        }
    }

    public class StockServiceClient
    {
        public StockServiceClient(InstanceContext ic)
        {
            Console.WriteLine("new StockServiceClient(" + ic + ")");
        }
    }

    // Define class which implements callback interface of duplex contract
    public class CallbackHandler
    {
        public static InstanceContext site = new InstanceContext(new CallbackHandler());
        public StockServiceClient proxy = new StockServiceClient(site);
        public CallbackHandler()
        {
            Console.WriteLine("new CallbackHandler()");
        }
        static CallbackHandler()
        {
            Console.WriteLine("static CallbackHandler()");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(CallbackHandler.site == null); // returns false
        }
    }
}

What is going on?

user437291
  • 4,561
  • 7
  • 37
  • 53

3 Answers3

3

The problem is with this line:

public static InstanceContext site = new InstanceContext(new CallbackHandler());

This line is really evil!

The static initialization of CallbackHandler must be finished before the new CallbackHandler() from the line given above is executed (because this would create an instance). But this line is implicitly a part of the static constructor! So I suppose the .NET runtime cannot execute this line, and leaves site uninitialized (or initialized later). That's why at the proxy initialization site is still null.

By the way, I am not sure if the order of static initializations is defined at all. Consider such an example:

class Test
{
    static Twin tweedledum = new Twin(tweedledee);
    static Twin tweedledee = new Twin(tweedledum);
}

Edit:
the paragraph 10.4.5.1 of C# language specs says that the static fields are initialized in the textual order, not considering the dependencies.

Edit:
Eureka! The part 10.11 of C# language specs clearly states:

It is possible to construct circular dependencies that allow static fields with variable initializers to be observed in their default value state.

What we did is indeed a circular dependency: CallbackHandler depends on itself. So the behaviour you get is actually documented and is according to the standard.

Edit:
Strange enough, when I test the code (here and here), I get static constructor running after instance constructor finishes. How is this possible?

Edit:
having got the answer to this question, I can explain what happens.

In the 1st case, your code is implicitly rewritten as

public static InstanceContext site;
public static ServiceReference1.StockServiceClient proxy;
static CallbackHandler()
{
    site = new InstanceContext(new CallbackHandler());
    proxy = new ServiceReference1.StockServiceClient(site);
}

In the 2nd case, you get

public static InstanceContext site;
public ServiceReference1.StockServiceClient proxy;
static CallbackHandler()
{
    site = new InstanceContext(new CallbackHandler()); // (*)
}
public CallbackHandler()
{
    proxy = new ServiceReference1.StockServiceClient(site);
}

In the 2nd case, the instance constructor in the line marked (*) runs before the completion of the static constructor (yes, it's possible), but at that point site is still not assigned.

So, basically in your second variant of code you have at each instance a separate proxy, which points to a static site, which in turn references some another "default" instance of CallbackHandler. Is that really what you want? Maybe, you just need to have site an instance field as well?

So, in the 2nd variant of the code the following happens:

  1. Main starts.
  2. Before the line CallbackHandler cbh = new CallbackHandler(); the static constructor of CallbackHandler is called
  3. The argument for new InstanceContext is calculated
    • The constructor new CallbackHandler() is executed
    • As a part of constructor, proxy is initialized with the new ServiceReference1.StockServiceClient(site), the value of site is null. This throws, but let's forget about this just now, and consider what would happen next.
  4. With the calculated argument, the constructor new InstanceContext is called
  5. The result of the constructor is assigned to site, which is now not null any more. This finishes the static constructor
  6. Now, the constructor called in Main can start.
    • As a part of it, a new proxy is constructed, now with non-null value of site
  7. The just created CallbackHandler is assigned to the variable cbh.

In your case, ServiceReference1.StockServiceClient(site) throws because site is null; if it wouldn't care about nulls, the code would run as it is described above.

Community
  • 1
  • 1
Vlad
  • 35,022
  • 6
  • 77
  • 199
  • A - So when CLR tries to instantiate an instance O ( which it would then assign to “site” ), it waits for static field “site” to get initialized, while “site” waits for O to get created, which in turn would initialize “site” field. Since this could create a deadlock of sort, static field site is “the wiser” and thus gets set to default value null?! B - Perhaps a stupid question, but I assume the instantiation of O wasn’t complited by runtime and thus O never actually existed ( hope question makes some sense )? – user437291 Nov 10 '10 at 20:25
  • 1
    I tried the code and see something completely strange. Example [with static proxy](http://ideone.com/T8KzH) and [with instance proxy](http://ideone.com/7B5Gr). It seems that the `CallbackHandler` is constructed **before** the static constructor finishes! This I don't understand--is it a bug or a feature? – Vlad Nov 10 '10 at 20:35
  • 1
    A: from the last documentation link (10.11) it seems that in case of "deadlock" something is going to be just uninitialized (or initialized later). I assume that in our case it's `site`. – Vlad Nov 10 '10 at 20:37
  • 1
    B: I assume that the instantiation of O must complete sooner or later. The test runs (see the comment #2) show completely strange behaviour: instance constructor happens to run before the static one! Hope someone from C# gurus can explain this. – Vlad Nov 10 '10 at 20:43
  • Latelly I haven't had much luck with gurus...see how many questions with zero replies I have ( and yes, I am feeling sorry for myself :D ) – user437291 Nov 10 '10 at 21:00
  • 1
    All the gurus seem to be sleeping already :) Let's wait for tomorrow. I'll try to find out the reason for the behaviour of the tests myself, too. Anyway, the initialization of static field with an instance of the class seems to be evil. – Vlad Nov 10 '10 at 21:10
  • 1
    I've created a related question: http://stackoverflow.com/questions/4150151/static-constructor-called-after-instance-constructor – Vlad Nov 10 '10 at 23:36
  • 1
    Yes, I can. Tried to answer your question. – Vlad Nov 11 '10 at 16:31
  • sorry for not replying sooner. Anyways, I really appreciate the time and the effort. Cheers mate – user437291 Nov 13 '10 at 18:34
3

By making the field non-static, you are associating each instance with the static instance, including the static instance itself.

In other words, you are trying to make an object that uses itself before it exists.

By making the field static, you disconnect proxy from the individual instance.
Therefore, the static instance (which must be created before proxy) doesn't try to create proxy, and it works.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    @user: If you create an instance in the static initializer, the constructor (including field initializers) runs immediately, before the static initializer finishes. When you write `static InstanceContext site = new InstanceContext(new CallbackHandler());`, the CLR will create a `CallbackHandler` instance, running its constructor, _and then_ assign the new instance to the `site` field. The constructor runs while `site` is still `null`. – SLaks Nov 11 '10 at 15:49
  • "The constructor runs while site is still null". I assume you mean instance constructor runs while "site" is still null and thus when "site" is passed as an argument to a "proxy" constructor,this constructor receives null. But you're saying that at later time "site" will still get initialized to a non-null value? – user437291 Nov 11 '10 at 16:17
  • 1
    @user: It would have, except that it threw an exception while initializing. – SLaks Nov 11 '10 at 16:19
1

When it is declared as static like that, you never called the constructor (at least in the code you have). It will only initialize the static member when you access it for the first time. I'm betting if you try to access it, you will get the same exception.

Bryan
  • 2,775
  • 3
  • 28
  • 40