[Translation] approaching. Net appdomain

Source: Internet
Author: User

Original article: Enter the. NET appdomain

Original Author: George P. Alexander Jr. (Software Engineer) published on:

 

God, the. NET Framework CLR is really clever! With the increasing number. net underlying programming, some complex and difficult details such as the architecture and processing process, completely impressed me. therefore, it is impossible to miss the beauty of the details we previously ignored. there is a core component that works side by side with CLR, called appdomain,. the appdomain part of the Net Framework is a very cool concept introduced by Microsoft.

 

For better understanding. net appdomain and appdomain affect the programs we create and work on. It is better to start from scratch. so let's start by clicking a button in the application. whenever we start an application, we actually start a Win32 process and run our program in this process. these processes use resources such as memory, objects, kernels, and so on. any Win32 process contains at least one thread (more and more threads later), and if we run other tasks or open other applications from our applications, all these tasks will belong to the Win32 process that runs the multi-thread set.

 

A feature of Win32 processes is that they are similar to virtual boundaries. it is easy to communicate within the process, but there are many restrictions to communicate with Win32 outside the process at a certain level. in order to communicate with other Win32 processes, we need some special working mechanisms, because security contexts needs to be considered in some security contexts and in specific systems, what can and cannot be done by Win32 processes.

 

Who is responsible for running a process? What are the factors involved in the successful running of a process? The execution of the process and the running of our code in the process are:Domain (Domain) and operating system privileges. When maintaining an active process, the operating system has to handle many complex situations and highlights.

Let's take a look at the actual situation:

Consider the following situation: One of our servers hosts many web applications, or we may have to run a bunch of Windows applications in our system. now, let's look at what we are working on. Let's look at what we have to give to these applications-resources, resources, and even more resources! Our resources (memory) are very expensive (this reminds me of the time when I played the game destroyer of the classic id software company, I have to disable the smartdrv.com program of MS-dos 6.2 on the 486pc with 4 MB memory at a time of 66 MHz. memory was a pure luxury ). in addition, when we run programs for different customers at the same time, security problems began to emerge. therefore, we urgently need to completely prohibit inter-process communication between these applications in any way (however, this is always in conflict with requirements .). this will lead to frequent crashes (Oh, I am used to such windows !) A process often uses up the memory requested by another process and then crashes! I hate crash! Everyone hates crash! (Of course, except Microsoft, which has maintained their market through the new version released continuously ). in any case, our process is terrible. nothing new. These frequent crashes and runtime errors are usually caused by memory leaks caused by inefficient memory usage, empty object references, and out-of-bounds memory. as a result, we are increasingly aware that it is very expensive to run and maintain processes created in a multi-user environment. therefore, running a large number of processes is not a good idea, because they are not very adaptive.

 

In this case, a very sophisticated solution came into being. running multiple applications in the same host process allows us to use less resources. this may even lead to a faster execution speed. however, there is another scenario that occurs every day: once an application crashes, all other applications in the same process will end up playing like a card!

 

Yes, we are talking about this domino effect.

 

What should we do now?

 

Use. net appdomain. this concept is clever, innovative, and worthy of the Nobel Prize. the main purpose of introducing application domain is to isolate our applications from other applications. application domains runs in a separate Win32 process. similar to the solution we just talked about, we run our applications in the application domain to limit errors and crashes caused by memory leaks.

 

Therefore, we run an application in an application domain, and we run multiple application domains simultaneously in a single Win32 process. with the ability of CLR to run hosted code, we can further reduce leaks and crashes (thanks to the CLR Garbage Collector ). objects in the same application domain can communicate with each other directly, but objects in different application domains can communicate with each other, it is necessary to copy objects to each other or use a proxy for message exchange (by referencing ).

This is the key to application domain. but there are more. application domain is equivalent to a lightweight process that runs in a single Win32 process. in fact, as we mentioned above, we can run multiple application domains in A Win32 process. another advantage of appdomain is that we can use the host (such as ASP. and does not affect the appdomain stored in the process. therefore, our work in application domain is independent. furthermore, we can destroy the appdomain to unload the objects loaded into that appdomain. amazing. when running. net, take over the control of the memory to forcibly use the appdomain Separation Mechanism. Therefore, all the memory used in the appdomain In the Win32 process is.. Net runtime management. in this way, we can avoid all the problems mentioned at the beginning, such as one application accessing the memory of another application, this avoids running errors caused by crashes. therefore, we actually applied a security layer to isolate the current application from other applications. in fact, when we create an application similar to running Web Services, application domain plays a key role in security and basic aspects.

 

So our appdomain should win the Nobel Prize, especially for. NET Framework. Now let's take a look at how to create a basic application domain.

 

A piece of cake, actually .. net Framework provides a beautiful base class, which exists in the system namespace, through which we can explicitly create an appdomain. in our application, Inherit System. extends albyrefobject base class. We can create objects that can communicate between different application domains.

Let's take a look at this. A helloworld application that uses C # To create appdomain. We use Windows console programs.

Note: The following Code cannot be run directly in Visual Studio. There is a similar but more descriptive code on msdn, which is posted at the end of this Article for your reference .]

using System;using System.Reflection;using System.Runtime.Remoting;public class ShowAppDomain : MarshalByRefObject{    public string GetAppDomainName()    {        return AppDomain.CurrentDomain.FriendlyName; // gets the Current application domain thread                                                      //and returns it's nameAppDomain name    }}public class CallMyHelloWorld{    public static void Main()    {        AppDomain ad = AppDomain.CreateDomain("Yupee! My AppDomain!"); // create a new domain        ShowAppDomain ad2 = (ShowAppDomain)ad.CreateInstanceAndUnwrap(            Assembly.GetCallingAssembly().GetName().Name, "ShowAppDomain");        /*        We use the AppDomain.CreateInstanceAndUnwrap method to Create a new instance of a specified type.        Assembly.GetCallingAssembly().GetName().Name returns The assembly object and          *the name of the method that calls the presently executing method.        */        Console.WriteLine("Here's my own AppDomain " + ad2.GetAppDomainName()); // Voila!    }}

 

Some appdomain usage involves the remoting of Web services. In fact, even our own. ASP. NET applications are also created in the application domain and exist in the worker's journey (w3wp.exe ).

 

It has been good till now. it's like starting to eat a mackineburg combination, plus French fries, sweet and juicy inner, perfect salty and crisp appearance, and thinking about this meal, other things are more delicious!

[Note: The appdomain introduction code on msdn can be pasted to the console program of Visual Studio for running and viewing .]

using System;using System.Reflection;using System.Threading;class Module1{    public static void Main()    {        // Get and display the friendly name of the default AppDomain.        string callingDomainName = Thread.GetDomain().FriendlyName;        Console.WriteLine(callingDomainName);        // Get and display the full name of the EXE assembly.        string exeAssembly = Assembly.GetEntryAssembly().FullName;        Console.WriteLine(exeAssembly);        // Construct and initialize settings for a second AppDomain.        AppDomainSetup ads = new AppDomainSetup();        ads.ApplicationBase =            System.Environment.CurrentDirectory;        ads.DisallowBindingRedirects = false;        ads.DisallowCodeDownload = true;        ads.ConfigurationFile =            AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;        // Create the second AppDomain.        AppDomain ad2 = AppDomain.CreateDomain("AD #2", null, ads);        // Create an instance of MarshalbyRefType in the second AppDomain.         // A proxy to the object is returned.        MarshalByRefType mbrt =            (MarshalByRefType)ad2.CreateInstanceAndUnwrap(                exeAssembly,                typeof(MarshalByRefType).FullName            );        // Call a method on the object via the proxy, passing the         // default AppDomain's friendly name in as a parameter.        mbrt.SomeMethod(callingDomainName);        // Unload the second AppDomain. This deletes its object and         // invalidates the proxy object.        AppDomain.Unload(ad2);        try        {            // Call the method again. Note that this time it fails             // because the second AppDomain was unloaded.            mbrt.SomeMethod(callingDomainName);            Console.WriteLine("Sucessful call.");        }        catch (AppDomainUnloadedException)        {            Console.WriteLine("Failed call; this is expected.");        }    }}// Because this class is derived from MarshalByRefObject, a proxy // to a MarshalByRefType object can be returned across an AppDomain // boundary.public class MarshalByRefType : MarshalByRefObject{    //  Call this method via a proxy.    public void SomeMethod(string callingDomainName)    {        // Get this AppDomain's settings and display some of them.        AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation;        Console.WriteLine("AppName={0}, AppBase={1}, ConfigFile={2}",            ads.ApplicationName,            ads.ApplicationBase,            ads.ConfigurationFile        );        // Display the name of the calling AppDomain and the name         // of the second domain.        // NOTE: The application's thread has transitioned between         // AppDomains.        Console.WriteLine("Calling from '{0}' to '{1}'.",            callingDomainName,            Thread.GetDomain().FriendlyName        );    }}/* This code produces output similar to the following: AppDomainX.exeAppDomainX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=nullAppName=, AppBase=C:\AppDomain\bin, ConfigFile=C:\AppDomain\bin\AppDomainX.exe.configCalling from 'AppDomainX.exe' to 'AD #2'.Failed call; this is expected. */

 

Note: I can see that the pen writing method is an old beauty, casual words and colloquial. It is quite casual with hip hop. This writing method is rare in Writing technical articles.

Related Article

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.