Use. NET is an executable program *.exe, which is not directly hosted into the process, but is hosted into the application domain (AppDomain). The application domain is. NET introduces a new concept, which is less than the resources consumed by the process and can be seen as a lightweight process. An application domain can have multiple threads, and a thread can also travel across multiple application domains.
In a process can contain multiple application domains, an application domain can be installed in an executable program (*.exe) or multiple assemblies (*.dll). This allows for deep isolation between application domains, even if an application domain in the process has an error that does not affect the normal functioning of other application domains.
When an assembly is called by multiple application domains at the same time, there are two situations:
- The CLR loads this assembly for different application domains, respectively.
- The CLR loads this assembly outside of all application domains and implements assembly sharing, which is a special case, known as Domain Neutarl.
Application domain: (application domain, abbreviation app domain) a logical container for a set of assemblies, one logical partition in a process. is typically created and manipulated by the runtime host. the only role of the AppDomain is to isolate.
Specific features:
- Isolation, an object created by code in an AppDomain cannot be accessed directly by code in another AppDomain. Achieve the effect of isolating applications. Of course, if you want to access content in another AppDomain, you can use the "Marshal by reference" or "marshal by value" semantics.
- The AppDomain can unload, but cannot unload individual assemblies or types, only the entire application domain. This unloads all the assemblies contained in the AppDomain.
- The AppDomain can be protected separately, and the AppDomain, when created, applies a permission set that determines the maximum permissions granted to assemblies running in this AppDomain. This protects the code that the host loads from being destroyed.
- Configurations can be implemented separately, and the AppDomain, when created, associates a set of configuration settings. These settings primarily affect how the CLR loads the assembly in the AppDomain. These settings involve search paths, version redirection, shadow copy, and loader optimizations.
conditions for using the AppDomain:
- Assemblies that require isolation, such as some code that is particularly prone to crashes, can be considered to run separately in a particular appDomain;
- Assemblies of different security levels, if you need to divide the boundaries of security enforcement for your code, consider creating separate security-level code in an appDomain that has different security information set
- In terms of performance, some assemblies can consume a lot of resources, although in a managed environment there is essentially no resource consumption vulnerability, but there is always a situation where access is dense and resource intensive at specific times, so consider creating a separate appDomain, after the resource consumption exceeds the critical point The AppDomain unloads, adapts the system operation request. The use of different AppDomain in ASP. NET is to prevent the crash of one application from affecting other ASP. While the non-restarted system does not restart IIS without affecting the ASP. Unloading a new appDomain at the same time, ideally enabling the web system to be online for a long time (which was formerly an expensive UNIX feature, was finally "borrowed" by MS).
- Run concurrently with different versions of the same application set. This is a big problem in the COM era, and now through the appDomain, you can achieve good compatibility by implementing two of different assemblies in a single process.
- Load some programs dynamically.
I. Properties and methods of the AppDomain
The AppDomain class exists under the System namespace for managing application domains.
Common properties of the AppDomain:
Property |
Description |
ActivationContext |
Gets the activation context for the current application domain. |
ApplicationIdentity |
Gets the application identity in the application domain. |
BaseDirectory |
Gets the base directory. |
CurrentDomain |
Gets the current application domain of the Thread. |
Id |
Gets an integer that uniquely identifies the application domain in the process. |
Relativesearchpath |
Gets the path relative to the base directory in which the Assembly resolver should probe the private assembly. |
Setupinformation |
Gets the application domain configuration information for this instance. |
Common methods of the AppDomain:
Method |
Description |
CreateDomain |
Create a new application domain. |
CreateInstance |
Creates a new instance of the specified type defined in the specified assembly. |
CreateInstanceFrom |
Creates a new instance of the specified type defined in the specified assembly file. |
DoCallback |
Executes code in another application domain that is identified by the specified delegate. |
ExecuteAssembly |
Executes the assembly contained in the specified file. |
ExecuteAssemblyByName |
Executes the assembly. |
Getassemblies |
Gets the assembly that has been loaded into the execution context of this application domain. |
GetCurrentThreadID |
Gets the current thread identifier. |
GetData |
Gets the value stored in the current application domain for the specified name. |
Isdefaultappdomain |
Returns a value that indicates whether the application domain is the default application domain for the process. |
SetData |
Assigns values to application domain properties. |
Load |
Load the Assembly into this application domain. |
Unload |
Uninstalls the specified application domain. |
AppDomain events:
Event |
Description |
AssemblyLoad |
Occurs when an assembly is loaded. |
Assemblyresolve |
Occurs when the parsing of an assembly fails. |
DomainUnload |
Occurs when the AppDomain is about to be uninstalled. |
ProcessExit |
Occurs when the parent process of the default application domain exists. |
Reflectiononlyassemblyresolve |
Occurs when the parsing of an assembly fails in the reflection-only context. |
Resourceresolve |
Occurs when resource resolution fails because the resource is not a valid linked resource or embedded resource in the assembly. |
Typeresolve |
Occurs when the parsing of a type fails. |
UnhandledException |
Occurs when an exception is not captured. |
Ii. loading assemblies in the AppDomain
A new application domain can be established through the CreateDomain method.
Here is an application domain created using CreateDomain and loading the assembly Model.dll using the Load method.
Finally, use the Getassemblies method to enumerate all the assemblies in this application domain.
public class program { static void Main (string[] args) { var domain = Appdomain.createdomain (" Myappdomain "); Domain. Load (@ "Console-learning Test"); foreach (var assembly in Domain. Getassemblies ()) { Console.WriteLine (assembly. FullName); } Console.readkey (); } }
The output results are as follows:
Note: When the assembly is loaded, it cannot be unloaded from the AppDomain, only the entire AppDomain can be unloaded.
You can use the ExecuteAssembly method when you need to load an executable program in the AppDomain.
For example, build a console program:
Class program { static void Main (string[] args) { Console.WriteLine ("For application domain execution! "); Console.readkey (); } }
Save the path generated by the above program to: C:\Users\ChenZhuo\Desktop\ConsoleApplication1\ConsoleApplication1\bin\Debug\ ConsoleApplication1.exe
Below we create an application domain and execute the above assembly:
public class program { static void Main (string[] args) { var domain = Appdomain.createdomain (" Myappdomain ");
Executes the specified assembly domain. ExecuteAssembly (@ "C:\Users\ChenZhuo\Desktop\ConsoleApplication1\ConsoleApplication1\bin\Debug\ ConsoleApplication1.exe "); Console.readkey (); } }
The output results are as follows:
Iii. Uninstalling the application domain
The AppDomain can be uninstalled via unload and the DomainUnload event will be triggered when the AppDomain unloads.
The following uses CreateDomain to establish an application domain named Newappdomain. The Assemblyload event processing method is then established to display the assembly information when the assembly is loaded. Finally, the DomainUnload event processing method is established, and the uninstall information is displayed when the AppDomain unloads.
Class program { static void Main (string[] args) { //New application domain AppDomain MyDomain = Appdomain.createdomain ("domain"); Establish AssemblyLoad event handling method Mydomain.assemblyload + = (sender, E) = { Console.WriteLine ("Assembly is loading! "+ E.loadedassembly.fullname); }; Establish Assemblyunload event handling method Mydomain.domainunload + = (sender, e) + = { Console.WriteLine ("Assembly is unloading!") "); }; Loading assembly mydomain.load ("MySpace"); Thread.Sleep (+); Console.WriteLine ("in Work!"); Uninstall the Assembly AppDomain.Unload (MyDomain); Console.readkey (); } }
The output results are as follows:
Iv. creating an object in an AppDomain that specifies classes in an assembly
Using the CreateInstance method, you can create an object of a specified class in an assembly. However, using this method returns a ObjectHandle object that can be called by the Unwrap method to convert this value to the original type.
The following example takes advantage of the Myspace.person object in the MySpace.dll assembly.
namespace consoleapplication1{public class program { static void Main (string[] args) { var person = (person) AppDomain.CurrentDomain.CreateInstance ("MySpace", "Myspace.person"). Unwrap (); Person. Id = 1; Person. Name = "Zhang Fei"; Console.WriteLine (person. Id + ":" + person. Name); Console.readkey ();}}}
Person:
namespace myspace{public class person {public int Id {get; set;} public string Name {get; set;}} }
The output results are as follows:
C # Learning Notes----AppDomain application domains