3.3 Avoid Loading Unnecessary Assemblies into Application Domains


Problem

You need to pass an object reference between code running in different application domains; however, you don't want the common language runtime (CLR) to load the object's type metadata into any intermediary application domain.

Solution

Wrap the object reference in a System.Runtime.Remoting.ObjectHandle and unwrap the object reference only when you need to access the object.

Discussion

When you pass a marshal- by-value (MBV) object across application domain boundaries, the runtime creates a new instance of that object in the destination application domain. This means that the runtime must load the assembly containing that type metadata into the application domain. Passing MBV references across intermediate application domains can result in the runtime loading unnecessary assemblies into application domains. Once loaded, these superfluous assemblies can't be unloaded without unloading the containing application domain. (See recipe 3.9.)

The ObjectHandle class allows you to wrap an object reference so that you can pass it between application domains without the runtime loading additional assemblies. When the object reaches the destination application domain, you can unwrap the object reference, causing the runtime to load the required assembly and allowing you to access the object as normal. To wrap an object (such as a System.Data.DataSet ), use the following statement:

 // Create a new DataSet. System.Data.DataSet data1 = new System.Data.DataSet(); // Configure/populate the DataSet. // Wrap the DataSet. System.Runtime.Remoting.ObjectHandle objHandle =      new System.Runtime.Remoting.ObjectHandle(data1); 

To unwrap the object, use the ObjectHandle.Unwrap method and cast the returned object to the correct type, as shown here.

 // Unwrap the DataSet System.Data.DataSet data2 =      (System.Data.DataSet)objHandle.Unwrap(); 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net