Showing posts with label See Sharp. Show all posts
Showing posts with label See Sharp. Show all posts

Relational lifted operators are confusing to me

| 3 comments

I am glad to know that I could access BlogSpot from my workplace (although not from my rental house), which means that I could continue writing something I feel interesting and worthy sharing.

Several months ago, we had a discussion internally about the operator lifting feature in C#, and how we could leverage upon this feature in our own library. Our library is mainly used for SI unit conversion, one requirement of this library is to support the basic arithmetic operations on those unit classes, for example, we have unit classes like Length, Time and Velocity, and we should support operation like follows:

Velocity = Length / Time, Length = Velocity * Time

Apparently, we could use the operator overloading feature in C# to enable the above scenarios, so that we could overload the division or multiplication operators as follows:

public static Length operator *(Velocity velocity, Time time)
{
    return velocity.Amount * time.Amount * Length.Meter;
}

This looks great and okay, but how about if the “velocity” or “time” parameter is null, then we end up having NullReferenceException thrown at us. The correct implementation should be something like the following:

public static Length operator *(Velocity velocity, Time time)
{
    if(velocity == null|| time == null)
    {
        return null;
    }

    return velocity.Amount * time.Amount * Length.Meter;
}

This just follows the rules when overloading operator which could be lifted as Eric Lippert illustrated in his blog post:

3) For the binary operators + - * / % & | ^ << >>, where the operator takes an S and a T and returns a U there is a corresponding lifted operator that takes an S? and a T? and returns a U?. It returns null if either argument is null.

I almost totally agree with the rules described by Eric Lippert except this one:

1) For every equality and relational operator that compares an S to a T and returns a bool there is a corresponding lifted operator that compares an S? to a T? and returns a bool. It returns false if either argument is null. (With the additional exception that if one argument to an equality operator is the null literal then the result may be determined by checking if the nullable term has a value.)

Consider this:

double? a = null;
double? b = 1;
Console.WriteLine(a > b);
Console.WriteLine(a == b);

Console.WriteLine(a < b);

This three comparison operation will all return false which doesn’t make any sense, since the three comparison should be mutually exclusive in logical sense.

Actually I recommend to return bool? when overloading those relational operators as follows:

public class Length
{
    public Length(double amount)
    {
        this.Amount = amount;
    }

    public double Amount
    {
        get;
        private set;
    }

    public static bool? operator >(Length a, Length b)
    {
        if(ReferenceEquals(a, null) || ReferenceEquals(b, null))
        {
            return null;
        }

        return a.Amount > b.Amount;
    }

    public static bool? operator <(Length a, Length b)
    {
        if(ReferenceEquals(a, null) || ReferenceEquals(b, null))
        {
            return null;
        }

        return a.Amount < b.Amount;
    }

    public static bool? operator ==(Length a, Length b)
    {
        if(ReferenceEquals(a, null) || ReferenceEquals(b, null))
        {
            return null;
        }

        return a.Amount == b.Amount;
    }


    public static bool? operator !=(Length a, Length b)
    {
        if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
        {
            return null;
        }

        return a.Amount != b.Amount;
    }
}

With this Length class at hand, then three comparisons shown previously will all return correct result (aka null):

Length a = null;
var b = new Length(1);
Console.WriteLine(a > b);
Console.WriteLine(a == b);

Console.WriteLine(a < b);

I’ve no idea why nullable type in C# doesn’t follow this, but they do have their own explanation which is even more confusing to me:

This seems like a very natural thing for a C# user to want to write. But if equality is three-valued, comparing anything to null always returns a null value (ie null isn't equal to anything), and therefore such a comparison can never succeed. Instead, the user would have to write:

if (!p.HasValue)

or something similar. We decided that the value of having a model that was consistent with the way users were used to dealing with reference null was pretty high, and therefore decided to make the relational operators return bool.

I personally think writing line like if(!p.HasValue) is okay for me, because otherwise I need to deal with other confusing scenario like the one I’ve shown above with three comparisons on double?.

Delegate.BeginInvoke vs ThreadPool.QueueUserWorkItem

| 3 comments

Today, I come across Chris Brumme's blog on TransparentProxy, I really enjoy his blog, in particular those dedicated to the inner-working of CLR, one of the surprising sentence I read from his TransparentProxy article is that:

One surprising fact is that this is also why Delegate.BeginInvoke / EndInvoke are so slow compared to equivalent techniques like ThreadPool.QueueUserWorkItem (or UnsafeQueueUserWorkItem if you understand the security implications and want to be really efficient). The codepath for BeginInvoke / EndInvoke quickly turns into the common Message processing code of the general remoting pathway.

   I have to say I get pretty stunned when reading this, so I write a little piece of code to verify his allegation:

using System;
using System.Threading;
using System.Diagnostics;

namespace DelegatePerformance
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart threadStart = new ThreadStart(() => { });
            WaitCallback waitCallback = new WaitCallback(a => { });
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            for (int i = 0; i < 10000; i++)
            {
                threadStart.BeginInvoke(null, null);
            }
            stopWatch.Stop();
            Console.WriteLine("Delegate.BeinInvoke(): {0}",stopWatch.ElapsedTicks.ToString());

            stopWatch.Reset();
            stopWatch.Start();
            for (int i = 0; i < 10000; i++)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(waitCallback);
            }
            stopWatch.Stop();
            Console.WriteLine("ThreadPool.QueueUserWorkItem(): {0}", stopWatch.ElapsedTicks.ToString());
        }
    }
}

And the following output is what I get when running above programme:

Delegate.BeinInvoke(): 591441
ThreadPool.QueueUserWorkItem(): 91958

From the output, there is no brainer that Delegate.BeginInvoke is way much slower than the ThreadPool.QueueUserWorkItem call.


 

AOP Style Thread Synchronization

| 0 comments

Whenever I encounter with the problem of threading, I always think that this aspect of programming problem should be directly built into the framework, so we shouldn't need to understand things like STA, MTA, cross threading marshaling etc. the System.Threading.SynchronizationContext and System.ComponentModel.AsyncOperationManager are designed just for this very purpose. But this solution is far from optimal, so I dig into it, and with the help of Don Box's Book Essential .NET-Common Language Runtime, I come up with an approach using CLR's method interception mechanism.

using System;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Services;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Messaging;

namespace ThreadBoundObjectDemo
{
    internal class SynchronizationProxy : RealProxy
    {
        private SynchronizationContext constructionContext;
        private readonly MarshalByRefObject target;
        private readonly Object syncRoot;
        public SynchronizationProxy(MarshalByRefObject target) : base(typeof(ThreadBoundObject))
        {
            this.target = target;
            this.syncRoot = new Object();
        }

        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage call = (IMethodCallMessage)msg;
            IMessage response = null;
            if (call is IConstructionCallMessage)
            {
                IConstructionCallMessage ctor = (IConstructionCallMessage)msg;
                constructionContext = SynchronizationContext.Current;
                RealProxy defaultProxy = RemotingServices.GetRealProxy(target);
                defaultProxy.InitializeServerObject(ctor);
                response = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, (MarshalByRefObject)this.GetTransparentProxy());
            }
            else
            {
                if (constructionContext == null || constructionContext.GetType() == typeof(SynchronizationContext))
                {
                    lock (this.syncRoot)
                    {
                        response = RemotingServices.ExecuteMessage(target, call);
                    }
                }
                else if (constructionContext != SynchronizationContext.Current)
                {
                    constructionContext.Send(new SendOrPostCallback(delegate
                    {
                        response = RemotingServices.ExecuteMessage(target, call);
                    }), null);
                }
                else
                {
                    response = RemotingServices.ExecuteMessage(target, call);
                }
            }

            return response;
        }
    }

    /// <summary>
    /// Indicates that all access on an object members(including fields, methods, properties, indexers etc) is thread safe.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class SynchronizedAttribute : ProxyAttribute
    {
        public override MarshalByRefObject CreateInstance(Type serverType)
        {
            MarshalByRefObject target = base.CreateInstance(serverType);
            SynchronizationProxy rp = new SynchronizationProxy(target);
            return (MarshalByRefObject) rp.GetTransparentProxy();
        }
    }
}

So if you want an object to be thread safe, all you need to do is to have a class subclass ContextBoundObject and apply the SynchronizedAttribute to it:

using System;
using System.Threading;
using System.Windows.Forms;

namespace ThreadBoundObjectDemo
{
    public class Program
    {
        [STAThread]
        public static void Main()
        {
            Button btn = new Button();
            btn.Text = "Text set on creation thread";
            Form frm = new Form();
            frm.Controls.Add(btn);
            btn.Dock = DockStyle.Top;
            ThreadBoundObject obj = new ThreadBoundObject(btn);
            btn.Click += delegate
            {
                Thread t = new Thread(new ThreadStart(delegate
                {
                    obj.ButtonText = "Text set from another thread";
                }));
                t.Start();
            };
            Application.Run(frm);
        }
    }

    [SynchronizedAttribute]
    public class ThreadBoundObject : ContextBoundObject
    {
        Button btn;
        public ThreadBoundObject(Button btn)
        {
            this.btn = btn;
        }

        public String ButtonText
        {
            get { return this.btn.Text; }
            set { this.btn.Text = value; }
        }
    }
}

 

To be honest, I don't like the design of ContextBoundObject, but suffice it to say, with the power of CLR's method interception mechanism, you can write AOP styled programme much easier, It looks like that you need to write more plumbing code to implement the AOP components, but you would wind up getting the benefit of easy usage pattern.

AOP Style Thread Synchronization

| 0 comments

Whenever I encounter with the problem of threading, I always think that this aspect of programming problem should be directly built into the framework, so we shouldn't need to understand things like STA, MTA, cross threading marshaling etc. the System.Threading.SynchronizationContext and System.ComponentModel.AsyncOperationManager are designed just for this very purpose. But this solution is far from optimal, so I dig into it, and with the help of Don Box's Book Essential .NET-Common Language Runtime, I come up with an approach using CLR's method interception mechanism.

using System;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Services;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Messaging;

namespace ThreadBoundObjectDemo
{
    internal class SynchronizationProxy : RealProxy
    {
        private SynchronizationContext constructionContext;
        private readonly MarshalByRefObject target;
        private readonly Object syncRoot;
        public SynchronizationProxy(MarshalByRefObject target) : base(typeof(ThreadBoundObject))
        {
            this.target = target;
            this.syncRoot = new Object();
        }

        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage call = (IMethodCallMessage)msg;
            IMessage response = null;
            if (call is IConstructionCallMessage)
            {
                IConstructionCallMessage ctor = (IConstructionCallMessage)msg;
                constructionContext = SynchronizationContext.Current;
                RealProxy defaultProxy = RemotingServices.GetRealProxy(target);
                defaultProxy.InitializeServerObject(ctor);
                response = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, (MarshalByRefObject)this.GetTransparentProxy());
            }
            else
            {
                if (constructionContext == null || constructionContext.GetType() == typeof(SynchronizationContext))
                {
                    lock (this.syncRoot)
                    {
                        response = RemotingServices.ExecuteMessage(target, call);
                    }
                }
                else if (constructionContext != SynchronizationContext.Current)
                {
                    constructionContext.Send(new SendOrPostCallback(delegate
                    {
                        response = RemotingServices.ExecuteMessage(target, call);
                    }), null);
                }
                else
                {
                    response = RemotingServices.ExecuteMessage(target, call);
                }
            }

            return response;
        }
    }

    /// <summary>
    /// Indicates that all access on an object members(including fields, methods, properties, indexers etc) is thread safe.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class SynchronizedAttribute : ProxyAttribute
    {
        public override MarshalByRefObject CreateInstance(Type serverType)
        {
            MarshalByRefObject target = base.CreateInstance(serverType);
            SynchronizationProxy rp = new SynchronizationProxy(target);
            return (MarshalByRefObject) rp.GetTransparentProxy();
        }
    }
}

So if you want an object to be thread safe, all you need to do is to have a class subclass ContextBoundObject and apply the SynchronizedAttribute to it:

using System;
using System.Threading;
using System.Windows.Forms;

namespace ThreadBoundObjectDemo
{
    public class Program
    {
        [STAThread]
        public static void Main()
        {
            Button btn = new Button();
            btn.Text = "Text set on creation thread";
            Form frm = new Form();
            frm.Controls.Add(btn);
            btn.Dock = DockStyle.Top;
            ThreadBoundObject obj = new ThreadBoundObject(btn);
            btn.Click += delegate
            {
                Thread t = new Thread(new ThreadStart(delegate
                {
                    obj.ButtonText = "Text set from another thread";
                }));
                t.Start();
            };
            Application.Run(frm);
        }
    }

    [SynchronizedAttribute]
    public class ThreadBoundObject : ContextBoundObject
    {
        Button btn;
        public ThreadBoundObject(Button btn)
        {
            this.btn = btn;
        }

        public String ButtonText
        {
            get { return this.btn.Text; }
            set { this.btn.Text = value; }
        }
    }
}

 

To be honest, I don't like the design of ContextBoundObject, but suffice it to say, with the power of CLR's method interception mechanism, you can write AOP styled programme much easier, It looks like that you need to write more plumbing code to implement the AOP components, but you would wind up getting the benefit of easy usage pattern.

Some Rambles On Singleton Pattern

| 0 comments

Singleton design pattern is a widely discussed topic among the blogspere, and there are many good articles dedicated to this massively applied design pattern, such as Implementing the Singleton Pattern in C# and The "Double-Checked Locking is Broken" Declaration. Just recently, I came across a relatively old blog article by Brad Abrams talking about how to make double checked locking Singleton pattern work properly in C#. With all those splendid reading as backbone, I add another two ways of implementing double checked locking pattern.

My first approach is mutated from the memory barrier trick Brad talked about in his blog article:

public sealed class Singleton
{
    private static Object syncRoot = new Object();
    private static Object instance;

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            Singleton temp = null;
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        temp = new Singleton();

                        //Fully publish the Singleton object in memory to make it visible to all processors.
                        System.Threading.Thread.VolatileWrite(ref instance, temp);
                    }
                }
            }
            return temp;
        }
    }
}

Since Thread.VolatileWrite() method will do exactly what Thread.MemoryBarrier() does, so this approach is nothing different from Brad's.

Another approach to properly implement double checked locking is using TLS (Thread Local Storage) as The "Double-Checked Locking is Broken" Declaration article demonstrates. The original implementation is using Java, when implementing this approach in C#, you can get additional benefit out of ThreadStaticAttribute:

public sealed class Singleton
{
    [ThreadStatic]
    private static Int32 syncFlag = 0;
    private static Object syncRoot = new Object();
    private static Singleton instance;

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (syncFlag == 0) // Is the current thread online?
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }

                syncFlag = 1; // Indicate the current thread is online
            }
            return instance;
        }
    }
}  


Although, theoretically speaking, the two implementations shown above "should" work as expected, but without heavy testing on different hardware configurations, no one can make this guarantee:)

Virtual Method Performance

| 0 comments

Bart J.F. De Smet just blogs about the performance discrepancy when calling vitual methods and non-virtual methods, in his original testing code, he just compares calling virual methods and non-virtual methods through class-based references, actually calling virtual methods through interface-based references will also incur additional performance overhead, I modify his original code to include the testing snippet for calling virtual methods through interface-based reference:

using System;
using System.Diagnostics;

interface IFoo
{
    void Do();
}

class Virt : IFoo
{
    public virtual void Do() { }
    public void DoIt() { }

    static void Main()
    {
        Virt v = new Virt();

        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (int i = 0; i < 1000000000; i++)
            v.DoIt();
        sw.Stop();
        Console.WriteLine("Calling non-virtual method:{0}", sw.Elapsed);

        sw.Reset();
        sw.Start();
        for (int i = 0; i < 1000000000; i++)
            v.Do();
        sw.Stop();
        Console.WriteLine("Calling virtual method using class-based reference:{0}", sw.Elapsed);

        sw.Reset();
        sw.Start();
        IFoo f = v as IFoo;
        for (int i = 0; i < 1000000000; i++)
            f.Do();
        sw.Stop();
        Console.WriteLine("Calling virtual method using interface-based reference:{0}", sw.Elapsed);
    }
}
 

When compiling the above code using "csc /o /target:exe test.cs", and running it, I get the following output from the console:

Calling non-virtual method:00:00:01.6662637
Calling virtual method using class-based reference:00:00:03.9324559
Calling virtual method using interface-based reference:00:00:05.6118531

And when examining the compiled MSIL code using ildasme.exe, the callvirt opcode is used in the three testing snippets:

IL_0017: callvirt instance void Virt::DoIt() //v.DoIt()

IL_0054: callvirt instance void Virt::Do() //v.Do()

IL_0096: callvirt instance void IFoo::Do() //f.Do()

You can see that the three callvirt calls will result in three different performance results, I don't plan to explain why it works this way, because all I know about virtual method dispatching in CLR is learnt from Don Box's Essential .NET: Common Language Runtime, this book give a complete treatment on virtual methods and how it works.