C# .NET AppDomains

Create a single instance of an application domain.

/* Dirt simple usage:
 *  1. AppDomain.Create 
 *  2. AppDomain.SetData
 *  3. AppDomain.DoCallBack
 *  4. AppDomain.Unload
 */

namespace AppDomains
{
    class Program
    {
        static void Main(string[] args)
        {
            MySerializedData serialData = new MySerializedData();

            //Create domain and assign a name.  The spawned domain can read it's own name.
            System.AppDomain domain = System.AppDomain.CreateDomain("MY NEW DOMAIN");

            //SetData applies a dictionary like Key, Value pairs to the domain.
            domain.SetData("MyDataObj", serialData);
            domain.SetData("stringData", "Hi there.");
            domain.SetData("intData", 999);

            //Invoke, or start, the STATIC method via callback
            domain.DoCallBack(MyDomainCallback);

            //clean up
            System.AppDomain.Unload(domain);

            System.Console.ReadLine();
        }

        //Static Callback method for AppDomain.DoCallBack
        public static void MyDomainCallback()
        {
            //Get current domain
            System.AppDomain domain = System.AppDomain.CurrentDomain;

            string name = domain.FriendlyName;
            string threadID = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();

            //Get my data passed via key value pairs
            MySerializedData d = (MySerializedData)domain.GetData("MyDataObj");
            string stringData = (string)domain.GetData("stringData");
            int intData = (int)domain.GetData("intData");

            //Display in consoles
            System.Console.WriteLine("MyData={{{0},{1},'{2}'}}, stringData='{3}', and intData={4} were passed to {5}, on thread ID: {6}",
                d.a.ToString(),
                d.b.ToString(),
                d.d,
                stringData,
                intData.ToString(),
                name,
                threadID);
        }
    }

    //Simple class used to pass data to the callback
    [System.Serializable]
    class MySerializedData
    {
        public int a = 3, b = 5;
        public string d = "xxx";
    }
}

David Gregory Medina

Post created by: David Gregory Medina

Tagged with: , ,

Leave a Reply