Skip to content

Instantly share code, notes, and snippets.

@binki
Created November 3, 2016 16:12
Show Gist options
  • Save binki/de6a08fe57236ad6287882fd23b1bda4 to your computer and use it in GitHub Desktop.
Save binki/de6a08fe57236ad6287882fd23b1bda4 to your computer and use it in GitHub Desktop.
Remoting—reference versus value/AppDomain remoting
// Inspired by http://stackoverflow.com/q/13729089/429091
using System;
class Program
{
static void Main(string[] args)
{
var appDomain = AppDomain.CreateDomain("Temp AppDomain", null, AppDomain.CurrentDomain.SetupInformation);
try
{
var instance = appDomain.CreateInstanceAndUnwrap<RemoteRef>();
var value = new RemoteValue { Value = 2, };
instance.DoSomething(value);
Console.WriteLine(value.Value);
}
finally
{
AppDomain.Unload(appDomain);
}
}
}
static class AppDomainExtensions
{
public static T CreateInstanceAndUnwrap<T>(
this AppDomain appDomain)
where T : MarshalByRefObject
{
return (T)appDomain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName);
}
}
class RemoteRef
: MarshalByRefObject
{
public int Value { get; set; }
public void DoSomething(RemoteValue value)
{
value.Value += 3;
Console.WriteLine(value.Value);
}
}
// Won’t be able to access an instance of this remotely using CreateInstanceAndUnwrap
// because RPCs can only be made via MarshalByRefObjects. But you could pass this
// as a parameter to an RPC.
[Serializable]
class RemoteValue
{
public int Value { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment