Tag Archives: c#

Volatile variables

If You want to exit from loop if some bool set from another thread You may be victimed by compiler’s code optimalization.

class Test
{
    private bool _loop = true;

    public static void Main()
    {
        Test test1 = new Test();

        // Set _loop to false on another thread
        new Thread(() => { test1._loop = false;}).Start();

        // Poll the _loop field until it is set to false
        while (test1._loop == true) ;

        // The loop above will never terminate!
    }
}

Found here: http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

Enum.TryParse<> unexpected behaviour

Check code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace EnumTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TestEnum result;

            bool ret = Enum.TryParse<TestEnum>("Yellow", out result);
            // ret value becomes: false
 
            ret = Enum.TryParse<TestEnum>("111", out result);
            // ret value becomes: true, result becomes: 111 !!!!!
        }
    }
 
    enum TestEnum
    {
        Red = 1,
        Green = 2
    }
}

Something found in help:

“If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum. ”

Nice.

Lazy expression evaluation

What will we find in result after this code finished?

IEnumerable<string> src = new List<string> { "ab", "ac", "bc", "abc" };
List<string> filter = new List<string> { "a", "b", "c" };

foreach (var f in filter)
{
   src = src.Where(i => i.Contains(f));
}

result = src.ToList();

You say: only one element: “abc”?
Wrong!
It contains three elements: “ac”, “bc”, “abc”
Why?
Where() is lazy!
Excerpt from help:

“This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.”

We build a lazy evaluated expression chain there will be references to f variable. After we get out from cycle the reference to f remains in use, but it’s value will be the last one it got in the cycle.
So when we evaluate with ToList() call the src.Where(…).Where(…).Where(…) expression each lambda will look for “c”!

This behaviour changes in .NET 4.5; f will encapsulate the value and not the reference.

Task vs. CurrentThread

If You use Task and Thread.CurrentThread inside of the code tree callable from the task’s body You should know something.
The TaskScheduler may decide to run Your tasks on same Thread.
In this case Your code may not work as expected, see sample below:

private Dictionary<Thread, int> uniqueIds = new Dictionary<Thread, int>();
 
private void InitMyUniqueId(int id)
{
    // thread safety skipped to keep sample simple
    uniqueIds[Thread.CurrentThread] = id;
}
 
public void DoSomething()
{
    // thread safety skipped to keep sample simple
    var myUniqueId = uniqueIds[Thread.CurrentThread];
 
    Console.Write(myUniqueId);
}
 
public void main()
{
    var t1 = new Task(() =>
    {
        InitMyUniqueId(1);
        DoSomething();
    });
 
    var t2 = new Task(() =>
    {
        InitMyUniqueId(2);
        DoSomething();
    });
 
    t1.Start();
    t2.Start();
}

Depending on TaskScheduler the output can be “12” and “22” too!
The potential impact may be e.g. various context mismatches if You use CurrentThread
to select the local storage slot for Your data, etc. Be careful!

Possible workaround: check Task.CurrentId. If it is not null we are in a task
and using CurrentThread like above is dangerous.

BinaryFormatter and FormatterAssemblyStyle.Simple

Consider this code:

BinaryFormatter bf = new BinaryFormatter();
bf.AssemblyFormat = FormatterAssemblyStyle.Simple;
ret = bf.Deserialize(memoryStream);

Setting AssemblyFormat to FormatterAssemblyStyle.Simple should mean this:
“In simple mode, the assembly used during deserialization need not match exactly the assembly used during serialization. Specifically, the version numbers need not match as the LoadWithPartialName method is used to load the assembly.”
But this is not true if the assembly is signed!

My current solution:

using (MemoryStream ms = new MemoryStream(...))
{
    var versionMismatchAssemblyResolveHandler = new ResolveEventHandler((s,ea)=>
    {
        Assembly asm = Assembly.Load(new AssemblyName(ea.Name).Name);
        return asm;
    });
 
    try
    {
        AppDomain.CurrentDomain.AssemblyResolve += versionMismatchAssemblyResolveHandler;
 
        BinaryFormatter bf = new BinaryFormatter();
        bf.AssemblyFormat = FormatterAssemblyStyle.Simple;
        ret = bf.Deserialize(ms);
    }
    finally
    {
        AppDomain.CurrentDomain.TypeResolve -= versionMismatchAssemblyResolveHandler;
    }
}

This will workaround the situation emulate the behaviour.

Thread-safe lazy init pattern

The code below is not thread-safe:

class SomethingWithLazyProperty
{
        private OtherThing otherThing = null;
        public OtherThing OtherThing
        {
            get
            {
                if (this.otherThing == null)
                {
                    this.otherThing = new OtherThing();
                }
 
                return this.otherThing;
            }
        }
}

As You may see when two threads enter the getter and the thread switching occures while
both of them are inside the if block two OtherThings will be instantiated and only
one of them will be stored in private field for later uses.

You should use some locking mechanism to avoid this race condition. The appropriate mechanism
may depend on the heaviness of instantiation. Lets choose lock to get out something more
of this example:

class SomethingWithLazyProperty
{
        private object syncRoot = new object();

        private OtherThing otherThing = null;
        public OtherThing OtherThing
        {
            get
            {
                lock(syncRoot)
                {
                    if (this.otherThing == null)
                    {
                        this.otherThing = new OtherThing();
                    }
                }
 
                return this.otherThing;
            }
        }
}

Thread-safety now in place, but the code will be really slow because of
locking every time we use this property. Thread-safety was only important
once at the begining but we slowed down the code for the whole lifecycle!
Modify a little bit the body of getter:


            get
            {
                if (this.otherThing == null)
                {
                    lock(syncRoot)
                    {
                        if (this.otherThing == null)
                        {
                            this.otherThing = new OtherThing();
                        }
                    }
                }
 
                return this.otherThing;
            }

And voilá, the code is thread-safe and as fast as at the original!

if (something.Count() == 0) { … } construct

Do not use such a construct:

if (something.Count() == 0) 
{ 
   ... 
}

We are not interested in the real count of items in something.
Only the presence of items is the point of our interest.
So write instead of above this:

if (something.Any())
{
   ...
}

This will stop at the first item which will result in better performance in
cases where something contains a lot of items.