How to Execute Code in Another AppDomain

By Peter Bromberg

Illustrates the use of the DoCallback methods of AppDomain

// static DoCallback:

static string greetings = "PONG!";

public static void Main()
{
   AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");

    greetings = "PING!";
    MyCallBack();
    otherDomain.DoCallBack(new CrossAppDomainDelegate(MyCallBack));

    // Output:
    //   PING! from defaultDomain
    //   PONG! from otherDomain
}

static public void MyCallBack()
{
    string name = AppDomain.CurrentDomain.FriendlyName;

    if (name == AppDomain.CurrentDomain.SetupInformation.ApplicationName)
    {
        name = "defaultDomain";
    }
   Console.WriteLine(greetings + " from " + name);
}

// DoCallback By Value:

[Serializable]
public class PingPong
{
    private string greetings = "PING!";

    public static void Main()
    {
       AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");

        PingPong pp = new PingPong();
        pp.MyCallBack();
        pp.greetings = "PONG!";
        otherDomain.DoCallBack(new CrossAppDomainDelegate(pp.MyCallBack));

        // Output:
        //   PING! from defaultDomain
        //   PONG! from otherDomain
    }

    public void MyCallBack()
    {
         string name = AppDomain.CurrentDomain.FriendlyName;

        if (name == AppDomain.CurrentDomain.SetupInformation.ApplicationName)
        {
            name = "defaultDomain";
        }
       Console.WriteLine(greetings + " from " + name);
    }
}



How to Execute Code in Another AppDomain  (2442 Views)