Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception with Callback Handler if a field is an instance member

Tags:

c#

wcf

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?

like image 228
user437291 Avatar asked Feb 22 '26 01:02

user437291


2 Answers

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.

like image 60
Vlad Avatar answered Feb 26 '26 06:02

Vlad


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.

like image 30
SLaks Avatar answered Feb 26 '26 05:02

SLaks