Subscribe

RSS Feed (xml)

Pass Data Between Application Domains

You can pass data between application domains as arguments and return values when you invoke the members of objects that exist in other application domains. However, at times it's useful to pass data between application domains in such a way that the data is easily accessible by all code within the application domain.
Every application domain maintains a data cache that contains a set of name/value pairs. Most of the cache content reflects configuration settings of the application domain, such as the values from the AppDomainSetup object provided during application domain creation. (See here for more) You can also use this data cache as a mechanism to exchange data between application domains or as a simple state storage mechanism for code running within the application domain.
The SetData method allows you to associate a string key with an object and store it in the application domain's data cache. The GetData method allows you to retrieve an object from the data cache using the key. If code in one application domain calls the SetData or GetData methods to access the data cache of another application domain, the data object must support marshal-by- value or marshal-by-reference semantics or System.Runtime.Serialization.SerializationException is thrown. (See this post for details on the characteristics required to allow objects to transcend application domain boundaries.) This code demonstrates the use of the SetData and GetData methods by passing a System.Collections.ArrayList between two application domains.
using System;
using System.Reflection;
using System.Collections;

public class ListModifier {

    public ListModifier () {

        // Get the list from the data cache.
        ArrayList list = 
            (ArrayList)AppDomain.CurrentDomain.GetData("Pets");
        // Modify the list. 
        list.Add("turtle");
    }
}

public class PassDataExample {

    public static void Main() {

        // Create a new application domain.
        AppDomain domain = AppDomain.CreateDomain("Test");

        // Create an ArrayList and populate with information.
        ArrayList list = new ArrayList();
        list.Add("dog");
        list.Add("cat");
        list.Add("fish");

        // Place the list in the data cache of the new application domain.
        domain.SetData("Pets", list);

        // Instantiate a ListModifier in the new application domain.
        domain.CreateInstance("Recipe03-08", "ListModifier");

        // Get the list and display its contents.
        foreach (string s in (ArrayList)domain.GetData("Pets")) {
            Console.WriteLine(s);
        }

        // Wait to continue
        Console.ReadLine();
    }
}

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail