Stop bleeding!

In a conversation at work the other day, I used the phrase "marshal-by-bleed" and a couple of people hadn’t heard it before. There’s a good explanation here – in fact there’s tons of interesting CLR implementation information in Chris Brumme’s blog.
Marshal-by-bleed is a term for objects that are shared between AppDomains for reasons of efficiency or because the object is fundamental to the operation of the CLR and its identity needs to be preserved. Here’s a small example program that creates an AppDomain and runs a thread in this new domain which tries to lock some objects that are still locked in the original.

static void Main(string[] args)
AppDomain newDomain = AppDomain.CreateDomain("Test Runner");
  new Thread(delegate() { newDomain.DoCallBack(RunTest); }).Start();

static void RunTest()
Console.WriteLine("Tests starting");
if (!Monitor.TryEnter(typeof(Program)))
Console.WriteLine("The program type is locked");
if (!Monitor.TryEnter("fred"))
Console.WriteLine("The string is locked");
if (!Monitor.TryEnter(typeof(object)))
Console.WriteLine("object is locked");
Console.WriteLine("Tests done");

If you run the example, you see that the string instance and the object type are shared between the AppDomains, but the Program type is loaded afresh into the newly created AppDomain so that the lock on the Program type object has no effect inside this domain. 

You can get the Program type shared between the AppDomains by uncommenting the LoaderOptimization line.


This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s