application domain , do you really understand? What can it do?
When it comes to application domain AppDomain, the knowledge we have to know is the process, so what is a process? You might want to ask yourself how to define the process next. Here, I sell a xiaoguanzi first, you think first.
Let's first look at the process in Win7:
There are a lot of processes, and each process is like a program in the execution, either listening or executing or idle. This is also a basic concept in Windows systems, which has the system resources required for a running program such as allocating memory. And smart you must have tried, when you forcibly terminate a process, the other processes will not be followed by extinction, and the process is not mutually accessible (unless the use of distributed computing, which is something), Windows system, is to use the process to divide the work into multiple separate areas. At this point, you should have an answer to the above question. Right! A process is the basic boundary of a program.
So we're in. How is the process class handled in net?
First, we need to understand that system.diagnostics this namespace, there is a process class, it can be used to manage processes, such as Start,kill, access to the process of the module, get threads in the process, set the priority of the process and so on.
The following table shows the process common properties.
Basepriority |
Gets the base priority of the associated process. |
ExitCode |
Gets the value specified when the associated process terminates. |
Exittime |
Gets the time that the associated process exited. |
Handle |
Returns the native handle of the associated process. |
Handlecount |
Gets the number of handles opened by the process. |
HasExited |
Gets a value that indicates whether the associated process has been terminated. |
Id |
Gets the unique identifier of the associated process. |
MachineName |
Gets the name of the computer on which the associated process is running. |
Mainmodule |
Gets the main module of the associated process. |
Modules |
Gets the module that has been loaded by the associated process. |
PriorityClass |
Gets or sets the overall priority category of the associated process. |
ProcessName |
Gets the name of the process. |
StartInfo |
Gets or sets the property of the start method to pass to the process. |
StartTime |
Gets the time that the associated process started. |
SynchronizingObject |
Gets or sets the object that is used to marshal an event handler call that is emitted due to a process exit event. |
Threads |
Get a set of threads running in the associated process |
In addition to the above attributes, the process class also defines the following common methods:
Method |
Description |
GetProcessById |
Creates a new process component and associates it with an existing process resource that you specify. |
GetProcessByName |
Create more than one new process component and associate it with an existing process resource that you specify. |
GetCurrentProcess |
Gets the new process component and associates it with the currently active process. |
GetProcesses |
Gets a list of each process that is running on the local computer. |
Start |
Start a process. |
Kill |
Immediately stops the associated process. |
Close |
Frees all resources associated with this component. |
WaitForExit |
Instructs the process component to wait indefinitely for the associated process to exit. |
Let's write a few lines of code and try it.
The start and kill methods make it easy to create or destroy processes, and the following example is to start the Notepad process using the Start method and open the Test.txt file. After 2 seconds, use the Kill method to destroy the process and close Notepad.
void Main (string[] args) { Process process = Process.Start ("notepad.exe"Test.txt "); Thread.Sleep (a); process. Kill (); Console.read (); }
After running, open a Notepad and prompt you to close the Notepad after you have created test.txt,2 seconds.
Other, smart you can experiment on your own.
So there's a whole bunch of them, just to get to the---application domain that we want to know, you might ask, say a lot, why am I always talking about processes? Don't worry, look down slowly.
Use. NET-built executable program. EXE, which is not directly hosted in the process, but is hosted in the application domain (AppDomain), why not, because it is much less than the resources that the process consumes, we can even consider it a lightweight process.
Then you can understand the following: In a process, you can include multiple application domains, and an application domain can load one more executable program. exe or multiple assembly. dll. This enables deep isolation between application domains, and does not affect the normal operation of other application domains, even if an application domain in the process is faulty. (Do not mix with threads, the difference is quite big, you should be able to understand it and the relationship between the threads), with a picture to be sensible:
-----That's the problem-------
When an assembly is called by multiple application domains at the same time, what are the two situations that occur? :::::
----------------------------------------------------------First scenario: The CLR loads the assembly for a different application domain, respectively.
--------------------------------------------------------------------------------------------Second scenario: The CLR loads this assembly outside of all application domains , and to implement assembly sharing, this is a special case, known as Domain Neutral. Neutral
Referring to the process, and looking at the common properties and methods and events of the AppDomain, there is an AppDomain class in the System namespace that manages the application domain. The following are the common properties of the AppDomain class:
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. |
There are several methods in the AppDomain class that can be used to create a new application domain, or to execute an application in an application domain.
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. |
There are multiple events in the AppDomain class that govern different parts of the application domain life cycle.
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. |
Actual combat------------------------------------------------------------------------------------------>
As you can see, a new application domain can be established through the CreateDomain method. The following example creates an application domain using CreateDomain and loads the assembly using the Load method System.Web.Http.dll (which I randomly find, in the Bin folder by default, remember). Finally, use the Getassemblies method to enumerate all the assemblies in this application domain.
void Main (string[] args) { var appDomain = Appdomain.createdomain ("Test"); Appdomain.load ("System.Web.Http"); Parallel.ForEach (Appdomain.getassemblies (), assembly = {Console.WriteLine (assembly. FullName); }); Console.read (); }
Results:
However, it is important to note that once the assembly is loaded, it cannot be uninstalled directly, and the hosted AppDomain must be unloaded.
See the actual combat
The AppDomain can be uninstalled via unload and the DomainUnload event will be triggered when the AppDomain unloads.
In the following example, an application domain named Newappdomain will be created using CreateDomain. The Assemblyload event-handling method is then established to display the Assembly's information when the assembly is loaded. Finally, the DomainUnload event processing method is established, and the uninstall information is displayed when the AppDomain unloads.
Static voidMain (string[] args) {AppDomain Newappdomain= Appdomain.createdomain ("Newappdomain"); //establishing Assemblyload Event handling methodNewappdomain.assemblyload + = (obj, e) = ={Console.WriteLine (string. Format ("{0} is loading", E.loadedassembly.getname ())); }; //establishing Domainupload Event handling methodNewappdomain.domainunload + = (obj, e) = ={Console.WriteLine ("Newappdomain Unload"); }; //Loading AssembliesNewappdomain.load ("Chncharinfo"); //Uninstall AppDomainappdomain.unload (Newappdomain); Console.read (); }
Results:
------------------------------------------------------------------------
To deepen the impression, one more example: Creating an object in an assembly that specifies a class
Using the CreateInstance method, you can establish the alignment of the specified class in the assembly. However, using this method returns a ObjectHandle object that you can call the Unwrap method to convert the value to the original type.
The following example establishes the Model.person class in the Model.dll assembly.
Static voidMain (string[] args) { varperson = (person) AppDomain.CurrentDomain.CreateInstance ("Model","Model.person"). Unwrap (); Person.id=1; Person. Name="Test"; Person. Age= in; Console.WriteLine (string. Format ("{0} ' age is {1}", person. Name,person. Age)); Console.read (); }
Results:
Model.dll
namespacemodel{ Public classPerson { Public intID {Get;Set; } Public stringName {Get;Set; } Public intAge {Get;Set; } }}
At this point you should know what the application domain is, then is it over? Of course not! You should also know a finer-grained one . NET context . Here we have a sentence to explain the relationship between the three.
A process can host a set of related. NET assembly, and the application domain is a logical subdivision of the process. An application domain is further subdivided into multiple context boundaries, which are used for grouping purposes similar. NET object. Using the concept of context, the CLR is able to ensure that objects with special runtime requirements are properly controlled.
So what the context can do:
1: Context is used to host. NET object, all of the entities of the. NET objects are present in the context.
2: There is at least one default context in each AppDomain (context 0)
In general, the object that does not want to specify a particular context is called a contextual flexible object (context-agile), which does not require a specific operation and is only managed by the CLR itself, which is typically built into context 0.
. NET knowledge Comb---(Learn well. NET series)