Execute business logic in separate application domain

From time to time, I am trying to simplify code that I write on daily basis. One of the ideas that keeps bugging me is using more static stuff. As you may know, general rule of thumbs is to reduce static state, singletons and other static code. This is true. So everything I will write later should be considered as experimental.

One of the problems with static code is shared state. For example, you have class with static field, two threads access to it… and boom! you have permanently hidden problem. Traditional mitigation to this problem is just not to use static state. But what if we try to create static “instances”? If I am right we have two options, first is to just start new process and second is to create new AppDomain right in our current execution process. So I decided to give a try to second option. Test code is bellow:

using System;
using System.Diagnostics;

public class Program
{
    public static class Runner
    {
        public static int Test1 = 0;
        public static void CodeInChildAppDomain()
        {
            Console.WriteLine("Test {0} + {1}", 
                  AppDomain.CurrentDomain.FriendlyName, ++Test1);
        }
    }

    static void Main()
    {        
        var s = new Stopwatch();
        s.Start();

        for (var i = 0; i < 1000; i++)
        {
            var appDomain = AppDomain.CreateDomain("SecondAppDomain" + i);
            appDomain.DoCallBack(() =>
            {
                Runner.CodeInChildAppDomain();
                Runner.CodeInChildAppDomain();
            });    
        }

        s.Stop();
        Console.WriteLine("Average: {0}ms", s.Elapsed.TotalMilliseconds / 1000);       
    }
}

gist

Runner.CodeInChildAppDomain will run in child domain. Static field Test1 is for demonstration. Code will run 1000 cycles and average time is about 4ms. Adding Rx assembly to the Runner increased average up to 6ms.

Conclusion is simple, if 6ms is ok for each your operation you can try. Enjoy.

. .

Notes

  1. chaliy posted this