Relationships between processes, application domains, and contexts

Source: Internet
Author: User
Tags hosting

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.
You can include multiple application domains in a process, and an application domain can mount 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 first scenario is that the CLR loads this assembly for different application domains, respectively.
The second scenario: the CLR loads this assembly outside of all application domains and implements assembly sharing, which is a special case, called Domain Neutral.

--------------------------------------------------------------------------------------------------------------- -----------------------

Under the. NET platform, assemblies are not directly hosted in the process (whereas traditional Win32 programs are directly hosted). As a matter of fact. NET executable is hosted in a logical partition of a process, and the term is called an application domain (also known as an AppDomain). Visible, a process can contain multiple application domains, each hosting one in an application domain. NET executable program, the benefits are as follows:
The application domain is. The key features of the net platform operating system independence. This logical partitioning abstracts the differences in the execution of executable programs loaded by different operating systems.
The application domain has a much smaller CPU and memory footprint than a complete process. So the CLR loads and unloads the application domain much faster than the complete process.
Application domains provide deep isolation for hosted applications. If one of the application domains in the process fails, the other application domains will remain healthy.

Key members of the AppDomain:
CreateDomain (): This static method creates a new application domain in the current process. Because the CLR can create application domains as needed, there is little chance that this method must be called.
GetCurrentThreadID (): The static method returns the active thread ID on the current application domain.
UnLoad (): The static method unloads the specified application domain in the process.
BaseDirectory: Gets the base directory that is used to probe the associated assembly.
CreateInstance (): Creates a new instance of the specified type in the specified assembly file.
ExecuteAssembly (): Executes the assembly in the application domain based on the file name.
Getassemblies (): Gets the load that has been loaded into this application domain. NET assemblies (except for COM and C-based binaries).
Load (): Loads the assembly dynamically into the current application domain.

--------------------------------------------------------------------------------------------------------------- -----------------------

Properties and methods of 2.1 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.

Table 2.0

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.

Table 2.1

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.

Table 2.2

Third, in-depth understanding. NET context

3.1. The concept of the net context

An application domain is a logical partition that hosts assemblies in a process, and in an application domain there is finer granularity for hosting. NET object, that is. NET context.
All of them. NET objects exist in the context, and each AppDomain has at least one default context (context 0).
Objects that do not typically need to specify a particular context are called context-sensitive objects (context-agile), which do not require specific operations and are only managed by the CLR itself, and are generally built into the default context.

Figure 3.0

3.2 Transparent Proxy

In the context of the interface there is a message receiver is responsible for detecting interception and processing information, when the object is a subclass of MarshalByRefObject, the CLR will establish a transparent proxy, to achieve the transformation between the object and the message.
Application domains are the boundaries of resources in the CLR, and in general, objects in an application domain cannot be accessed by external objects. The function of MarshalByRefObject is to allow objects to be accessed across application domain boundaries in applications that support remoting, a parent class that is often used when using. NET Remoting remote object development.
This article addresses the role of processes and application domains, and the use of MarshalByRefObject has gone beyond the scope of this article, as reference to. NET Remoting remote Object development: "Review. NET Remoting distributed development".

3.3 Context Bindings

You can use the ContextBoundObject class when the system requires the object to use the message sink mechanism. ContextBoundObject inherits the MarshalByRefObject class, guaranteeing that its subclasses will be accessed through transparent proxies.
Described in the first section: the objects created by the generic class are contextual flexible objects (context-agile), which are automatically managed by the CLR and can exist in any context. An object created by a subclass of ContextBoundObject can only function correctly in the context in which it is established, and this state is called context binding. When other objects want to access the subclass object of the ContextBoundObject, they can only be manipulated by a surrogate transparency manager.

The following example is a comparison between a context-bound object and a flexible context object. Example is a normal class, and its objects run in the default context. The Contextbound class inherits the ContextBoundObject, and its object is a context-bound object. Contextbound also has a synchronization feature that guarantees that Contextbound objects are loaded into a thread-safe context. In addition, the context class has the Contextproperties property, which allows you to get the information that is already available for it.

1 class Program
2 {
3 public class Example
4 {
5 public void Test ()
6 {
7 contextmessage ("Example test\n");
8}
9//Access context-bound object test
public void Sync (Contextbound contextbound)
11 {
Contextbound.test ("Example call on contextbound\n");
13}
14}
15
[Synchronization]
public class Contextbound:contextboundobject
18 {
public void Test (String message)
20 {
Contextmessage (message);
22}
23}
24
static void Main (string[] args)
26 {
Example Example = new Example ();
Example. Test ();
Contextbound contextbound = new Contextbound ();
Contextbound.test ("Contentbound test\n");
Example. Sync (Contextbound);
Console.readkey ();
33}
34
35//Display contextual information
public static void Contextmessage (String data)
37 {
the context = Thread.currentcontext;
Console.WriteLine (String. Format ("{0}contextid is {1}", data, context.) ContextID));
The prop (Var) in context. Contextproperties)
Console.WriteLine (Prop. Name);
Console.WriteLine ();
43}
44}

Run results

It can be found from the running result that the example object will typically work only in the default context 0, while Contextbound will work in thread-safe context 1. When example needs to invoke the Contextbound object, it passes the message directly to context 1 through a transparent proxy.

Back to Catalog

Iv. process, application domain, thread interrelationships

4.1 Running code across the AppDomain

The data between application domains is relatively independent, and you can use the CrossAppDomainDelegate delegate when you need to execute assembly code in the current AppDomain in another AppDomain. After you delegate the CrossAppDomainDelegate method, the DoCallback method of the AppDomain executes the delegate.

1 static void Main (string[] args)
2 {
3 Console.WriteLine ("Currentappdomain start!");
4//Create a new application domain object
5 AppDomain Newappdomain = Appdomain.createdomain ("Newappdomain");
6//Binding CrossAppDomainDelegate Delegate method
7 crossappdomaindelegate crossappdomaindelegate=new crossappdomaindelegate (mycallback);
8//Bind DomainUnload event handling method
9 Newappdomain.domainunload + = (obj, e) = =
10 {
Console.WriteLine ("Newappdomain unload!");
12};
13//Call Delegate
Newappdomain.docallback (crossappdomaindelegate);
AppDomain.Unload (Newappdomain);
Console.readkey ();
17}
18
static public void Mycallback ()
20 {
String name = AppDomain.CurrentDomain.FriendlyName;
(int n=0;n<4;n++)
Console.WriteLine (String. Format ("Do work in {0} ...", name));
24}

Run results

4.2 Threads that span an AppDomain

A thread exists in a process, and it can run in several different AppDomain at different times. It is the basic unit of execution in the process, and the first thread that executes at the process entrance is considered the main path of the process. In. NET applications, the main () method is used as the portal, and when this method is called, the system automatically creates a main thread. Threads are primarily composed of CPU registers, call stacks, and thread local memory (thread locally storage,tls). The CPU registers primarily record the state of the currently executing thread, and the call stack is primarily used to maintain the memory and data that the thread invokes, and TLS is primarily used to hold the thread's state information.
Introduction to the thread, can refer to the "C # Comprehensive Disclosure-the details of multi-threaded (UP)", "C # Comprehensive disclosure--elaborate multithreading (bottom)"

The following example shows how to use a thread across an AppDomain, first creating a consoleapplication project, entering information about the current thread and application domain at execution time, and finally generating an executable program for Example.exe.

1         static void Main (string[] args)
2 {
3 var message = string. Format (" currentthreadid Is:{0}\tappdomainid is:{1}",
4 Thread.CurrentThread.ManagedThreadId, AppDomain.CurrentDomain.Id);
5 Console.WriteLine (message);
6 console.read ();
7 }

Then create a new Consoleapplication project in which to execute the Example.exe program in the new AppDomain, using the ExecuteAssembly method in this project.

1         static void Main (string[] args)
2 {
3 //Current application domain Information
4 Console.WriteLine ("Currentappdomain start!");
5 showmessage ();
6
7 //Create a new application domain object
8 AppDomain newappdomain = Appdomain.createdomain ("Newappdomain");
9 //Execute Example.exe in a new application domain
Ten newappdomain.executeassembly ("Example.exe");

appdomain.unload (Newappdomain);
Console.readkey ();
+ }

Public static void ShowMessage ()
+ {
var message = string. Format (" currentthreadid Is:{0}\tappdomainid is:{1}",
Thread.CurrentThread.ManagedThreadId, AppDomain.CurrentDomain.Id);
Console.WriteLine (message);
+ }

Run results

As can be seen, threads with ID equal to 9 run in AppDomain 1 and AppDomain 2, respectively, at different times.

4.3 Threads to the context

Threads can cross different contexts as well, if they can span the boundaries of an AppDomain.
In this example, the thread will run both in the default context and in the context that provides a thread.

1 class Program
2 {
3 [Synchronization]
4 public class Contextbound:contextboundobject
5 {
6 public void Test ()
7 {
8 ShowMessage ();
9}
10}
11
A static void Main (string[] args)
13 {
14//Current application domain Information
Console.WriteLine ("Currentappdomain start!");
ShowMessage ();
17
18//Running a thread in a context-bound object
Contextbound contextbound = new Contextbound ();
Contextbound.test ();
Console.readkey ();
22}
23
public static void ShowMessage ()
25 {
$ var message = string. Format ("Currentthreadid Is:{0}\tcontextid is:{1}",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentContext.ContextID);
Console.WriteLine (message);
29}
30}

Run results

This article summarizes

process, thread, application domain (AppDomain), context (contextual) Relationship 5.0, a process can include multiple application domains, or multiple threads, and threads can also travel through multiple application domains. At the same time, however, the thread is only in one application domain. Threads can also travel through multiple contexts, making calls to objects.

Although the process, application domain and context are not often used in common development, it is very meaningful to understand the relationship of the three, and to be familiar with its operation mode to utilize the resources of the system rationally and to improve the efficiency of the system.
In particular, the relationship between the three and the thread is particularly important, especially in a multithreaded system, if you can not clear their relationship and blindly use multi-threading, easy to cause resource preemption and deadlock and other errors.

Relationships between processes, application domains, and contexts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.