C # application domains and Assemblies

Source: Internet
Author: User
Tags data structures reflection

First, process processes:

A process is a basic concept in a Windows system that contains the resources needed to run a program. Processes are relatively independent, and one process cannot directly access the data of another process (unless you take advantage of distributed computing), the failure of one process does not affect the operation of other processes, and Windows systems use processes to divide work into separate regions. A process can be understood as a basic boundary of a program.

1. Establishment and destruction of processes:

static void Main (string[] args)
         {
             Process process = Process.Start ("notepad.exe", "File.txt");
             Thread.Sleep ();
             Process. Kill ();
        }
2. The process in which the computer is running:

static void Main (string[] args)
          {
             var processlist = process.getprocesses ()
                  . by (X=>x.id)
                 . Take (ten);
              foreach (Var process in processlist)
                 Console.WriteLine (String. Format ("ProcessID is:{0} \ t processname is:{1}",
                      process. Id, process. ProcessName));
              Console.readkey ();
         }
You can get the corresponding process through the GetProcessById method, or you may get a process of multiple corresponding names through the GetProcessByName method
3. Get all module modules in the process: These modules can be assemblies that end with *.dll, or can be executable programs at the end of *.exe

static void Main (string[] args)
         {
            var modulelist = process.getcurrentprocess (). Modules;
             foreach (System.Diagnostics.ProcessModule module in modulelist)
                 Console.WriteLine (String. Format ("{0}\n  url:{1}\n  version:{2}",
                     module. Modulename,module. Filename,module. fileversioninfo.fileversion));
            Console.readkey ();
         }

II. Assembly:

1. Definition: An assembly is a collection that contains one or more type definition files and resource files . It allows us to detach the logical representations and physical representations of reusable types.

2. Function:

2.1. Contains code that is executed by the common language runtime, and if the portable executable (PE) file does not have an associated assembly manifest, the Microsoft intermediate language (MSIL) code in the file is not executed. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main).

2.2. The Assembly forms a security boundary. An assembly is the unit in which permissions are requested and granted

2.3. The Assembly forms the type boundary. Each type of identity includes the name of the assembly on which the type resides. The type of MyType that is loaded within the scope of an assembly differs from the MyType types that are loaded within the scope of other assemblies.

2.4. The Assembly forms a reference scope boundary. The assembly's manifest contains the assembly metadata used to resolve the type and satisfy the resource request. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates the other assemblies on which it relies.

2.5. The Assembly forms the version boundary. An assembly is the smallest versioned unit in the common language runtime, and all types and resources in the same assembly are versioned into one unit. The assembly's manifest describes the version dependencies that you specify for any dependency assembly.

2.6. The Assembly forms the deployment Unit. When an application starts, only the assembly that is originally invoked by the application must exist. Other assemblies, such as localized resources and assemblies that contain utility classes, can be retrieved on demand. This allows the application to remain streamlined for the first download.

2.7. An assembly is a unit that supports parallel execution.

Assemblies can be static or dynamic. static assemblies can include. NET Framework types (interfaces and classes), as well as resources (bitmaps, JPEG files, resource files, and so on) for that assembly. Static assemblies are stored in portable executable (PE) files on disk. You can also use the. NET Framework to create dynamic assemblies, which run directly from memory and are not stored on disk until they are executed. You can save them on disk after the dynamic assembly is executed.

There are several ways to create assemblies. You can use the development tools used to create a. dll or. exe file, such as Visual Studio. NET. You can use the tools provided in the. NET Framework SDK to create assemblies with modules that are created in other development environments. You can also use the common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies.


3. Global assembly Cache:

Each computer that has the common language runtime installed has a computer-wide code cache called the global assembly cache. The global assembly cache stores assemblies that are specifically assigned to be shared by several applications on the computer.

Assemblies should be installed into the global assembly cache for sharing only when needed. The general principle is that the assembly dependencies remain private, and the assemblies are located in the application directory unless the shared assembly is explicitly required. Also, you do not have to install an assembly into the global assembly cache in order for COM interop or unmanaged code to access the assembly

There are two ways to deploy an assembly to the global assembly cache: A. Use an installer that is dedicated to the global assembly cache. This method is the preferred method of installing assemblies into the global assembly cache.
B. A development tool called the Global Assembly Cache tool (Gacutil.exe), which is provided using the Windows Software Development Kit (SDK).

Third, application domain:

Use. NET built executable program *.exe is not directly hosted in the process, but is hosted in the application domain (AppDomain). The application domain is a new concept of. NET introduction, which is less than the resources occupied by the process and can be viewed as a lightweight process.

you can include multiple application domains in one process , one application domain can load an executable program (*.exe) or multiple assemblies (*.dll), which enables deep isolation between application domains. Even if an error occurs in an application domain in a process, it does not affect the normal functioning of other application domains.

When an assembly is called by multiple application domains at the same time, two scenarios occur:
In the first case, the CLR loads the assembly for different application domains, respectively.
In the second case, the CLR loads this assembly outside of all application domains and implements assembly sharing, which is a special case called Domain Neutral.


1. Create a custom application domain:

The common language runtime host creates them automatically when an application domain is required. However, you can create your own application domains and load them into assemblies that need to be managed personally. You can also create an application domain from which to http://write.blog.csdn.net/postedit?type=edit execution code.

Namespace Attributetest
{
    class program
    {
        static void Main (string[] args)
        {
            Console.WriteLine ("Create new Domain");
            AppDomain domain = appdomain.createdomain ("MyDomain");
            Console.WriteLine ("Host domain:" +appdomain.currentdomain.friendlyname);//host Domain:AttributeTest.vshost.exe
            Console.WriteLine ("Child domain:" +domain.) FriendlyName);//Child Domain:mydomain
            Console.readkey ();}}}

2. Uninstall the application domain:

When you are finished using the application domain, you can uninstall it using the System.AppDomain.Unload method. The Unload method gracefully closes the specified application domain. During the uninstall process, no new threads can access the application domain, and all data structures specific to that application domain are freed. All assemblies loaded into the application domain are removed and can no longer be used, and if the assembly in the application domain is not domain-specific, the assembly's data remains in memory until the entire process is closed. In addition to shutting down the entire process, there is no mechanism to uninstall domain-neutral assemblies. In some cases, the request to unload the application domain does not work and results in cannotunloadappdomainexception.

         Console.WriteLine ("Creating New AppDomain.");
            AppDomain domain = appdomain.createdomain ("MyDomain", null);

            Console.WriteLine ("Host domain:" + AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine ("Child domain:" + domain.) FriendlyName);
            AppDomain.Unload (domain);
            Try
            {
                Console.WriteLine ();
                Console.WriteLine ("Host domain:" + AppDomain.CurrentDomain.FriendlyName);
                The following statement creates an exception because the domain no longer.
                Console.WriteLine ("Child domain:" + domain.) FriendlyName);
            }
            catch (appdomainunloadedexception e)
            {
                Console.WriteLine (E.gettype ()). FullName);
                Console.WriteLine ("The AppDomain MyDomain does not exist.");
            }
            Console.readkey ();

3. Configure the application domain:

You can use the AppDomainSetup class to provide the common language runtime with configuration information for the new application domain, and the AppDomainSetup ApplicationBase attribute defines the root directory of the application, and when the CLR needs to satisfy the type request,

It probes for an assembly containing that type in the directory specified by the ApplicationBase property.

            AppDomainSetup domaininfo = new AppDomainSetup ();
            Domaininfo.applicationbase = "C:\Users\v-lozhu\Documents\Visual Studio 2015\projects\mytestprojects\attributetest" ;
            AppDomain domain = appdomain.createdomain ("MyDomain", null,domaininfo);

            Console.WriteLine ("Host domain:" + AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine ("Child domain:" + domain.) FriendlyName);
            Console.WriteLine ("Application base is:" + domain.) Setupinformation.applicationbase);
            Unload the application domain.
            Console.readkey ();
4. To load an assembly into an application domain:

How to load an assembly into an application domain:

A.assembly.load (AssemblyName); Use the assembly name to load into the application domain as a common method.

B.assembly.loadfrom (): Loads the assembly given its file location, which loads the assembly using a different load context.

C.assembly.reflectiononlyload and Assembly.reflectiononlyloadfrom: Loading assemblies into the reflection-only context , which can be examined (but not executed) into assemblies that are loaded into the context. Also allows you to check for assemblies that target other platforms.

D.appdomain's CreateInstance and Createinstanceandunwrap methods.

E.type.gettype () Loading assemblies

The F.appdomain Load method loads the assembly. Used primarily for COM interoperability, you should not use this method to load an assembly into an application domain other than the application domain from which the method is invoked.

Namespace Attributetest
{
    class program
    {
        static void Main (string[] args)
        {
            Assembly a = < Strong>assembly.load</strong> ("ExampleTest.exe");
            Type MyType = A.gettype ("Exampletest.example");//name = "Example" FullName = "Exampletest.example" MethodInfo
            MyMethod = Mytype.getmethod ("MethodA");
            Object obj = Activator.CreateInstance (myType);
            Mymethod.invoke (obj, null);
            Console.readkey ();}}

static void Main (string[] args)
         {
            var appDomain = Appdomain.createdomain ("Newappdomain");
             <strong>appDomain.Load</strong> ("Model");
             foreach (var assembly in Appdomain.getassemblies ())
                 Console.WriteLine (String. Format ("{0}\n----------------------------",
                    Assembly.) FullName));
             Console.readkey ();
         }
<p>//You can use the ExecuteAssembly method when you need to load an executable program in AppDomain. </p>appdomain.executeassembly ("Example.exe")

       static void Main (string[] args)
        {
          var person = (person<strong>) Appdomain.currentdomain.createinstance</strong> ("Model", "Model.person"). Unwrap ();
            Person.id = 1;
            Person. Name = "ddd";
            Person. Age =;
            Console.WriteLine (person. Name);
            Console.readkey ();
        }


5. Get type and member information from the assembly:

            Type MyType = Type.GetType ("System.IO.BinaryReader");
            memberinfo[] Infos = mytype.getmembers (BindingFlags.Public | BindingFlags.NonPublic | bindingflags.static | BindingFlags.Instance | BINDINGFLAGS.DECLAREDONLY);
            Console.WriteLine ("Members Count" +infos.) Length);
            Console.WriteLine ("Full Name" +mytype.fullname);
            foreach (MemberInfo item in infos)
            {
                Console.WriteLine ("\ n" +item. Name);
            Console.readkey ();

6. Image replication assembly:

The common language runtime locks the assembly file when the assembly is loaded, so you can update the assembly for this application domain only if you uninstall the application domain to update the assembly, with shadow copies, without uninstalling the application domain.

When an application domain is configured to shadow copy, the assembly in the application path is replicated to another location and is loaded from this location, but the original assembly file is unlocked and can be updated.

Only assemblies stored in the application directory or in its subdirectories are available for shadow copying, which are specified by ApplicationBase and Privatebinpath when the application domain is configured. An assembly stored in the global assembly cache cannot be shadow copied.

6.1. Enable Shadow copy:

  AppDomainSetup domaininfo = new AppDomainSetup ();
  Domaininfo.shadowcopyfiles = "true";


Iv.. NET Context Contexts:

1. The application domain is a logical partition that hosts the assembly in the process, and there is a finer granularity for hosting in the application domain. NET object, that is. NET context contexts. All. NET objects exist in the. NET context, with at least one default context (CONTEXT0) in each AppDomain, : Objects created by generic classes are context-flexible objects (context-agile) that are automatically managed by the CLR and can exist in any context.


2. Transparent Agent:

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, implementation of the object and message conversion.
An application domain is the boundary of a resource in the CLR, and in general, an object in an application domain cannot be accessed by an external object. The function of MarshalByRefObject is to allow access to objects across application domain boundaries in applications that support remoting, a parent class that is often used when using. NET Remoting remote object development.

3. Context Binding:

The ContextBoundObject class can be used when the system requires the object to use the message sink mechanism. ContextBoundObject inherits the MarshalByRefObject class, ensuring that its subclasses are accessed through transparent proxies .

The objects established by the generic class are context-flexible objects (context-agile), which are automatically managed by the CLR and can exist in any context. An object created by a ContextBoundObject subclass, called a context-bound object, can only run correctly in the corresponding context in which it is established, which is called a context binding. When other objects want to access the subclass object of the ContextBoundObject, they can only manipulate it by acting on transparency. Contextbound also has a synchronization feature that guarantees that the Contextbound object is loaded into a thread-safe context to run

 Class Program {static void Main (string[] args) {Example Example = new Example (); Example.
            Test ();
            Mycontextbound bouind = new Mycontextbound (); Bouind.
            Test ("Contextbound test"); Example.
            Sync (Bouind);
        Console.readkey (); The public class Example {public void Test () {contextmessage ("Exa
            Mple test\n ");
            public void Sync (<strong>mycontextbound contextbound</strong>)/agent for incoming Mycontextbound
            {contextbound.test ("Example call on contextbound\n"); } [synchronization] public class Mycontextbound:contextboundobject {Publ
            IC void Test (String message) {contextmessage (message);
           }//Show context information public static void Contextmessage (string data) { Context context = Thread.currentcontext; Console.WriteLine (String. Format (' {0}contextid is {1} ', data, context.
            ContextID)); foreach (Var prop in the context.) Contextproperties) Console.WriteLine (prop).
            Name);
        Console.WriteLine (); }

    }

If you call its test method directly in the example class with an mycontextbound example, you cannot invoke it, and you can access the Mycontextbound object only through a proxy.

V. Process, thread, AppDomain,. NET context:

1. Run code across AppDomain:

The data between application domains is relatively independent, and you can use crossappdomaindelegate delegates when you need to execute assembly code in the current AppDomain in other AppDomain. After the CrossAppDomainDelegate delegate binding method, the delegate can be executed through the AppDomain DoCallback method.

Class program
    {
        static void Main (string[] args)
        {
            Console.WriteLine ("Currentappdomain start!");
            Create a new application domain object
            AppDomain newappdomain = Appdomain.createdomain ("Newappdomain");
            CrossAppDomainDelegate crossappdomaindelegate = new CrossAppDomainDelegate (mycallback);

            Newappdomain.docallback (crossappdomaindelegate);

            Newappdomain.domainunload + = (obj, e) =>
            {
                Console.WriteLine ("New Domain unload!");

            AppDomain.Unload (newappdomain);
            Console.readkey ();

        }
        static public void Mycallback ()
        {
            string name = AppDomain.CurrentDomain.FriendlyName;
            for (int n = 0; n < 4; n++)
                Console.WriteLine (String. Format ("Do  work in {0} ...", name);
        }
    
2. Threads across AppDomain:

Threads exist in the process and can run in several different AppDomain at different times. It is the basic unit of execution in a process, and the first thread that executes at the process portal is considered the main path of the process. In a. NET application, the main () method is used as the portal, and the system automatically creates a main thread when this method is called. Threads consist primarily of CPU registers, call stacks, and thread local memory (thread native STORAGE,TLS). CPU registers mainly record the state of the currently executing thread, the call stack is used primarily to maintain the memory and data that the thread calls, and TLS is used primarily to hold the thread's state information.

First, create a consoleapplication project, enter the current thread and application domain information at the time of execution, and finally generate the Example.exe executable program.

Class program
    {
        static void Main (string[] args)
        {
            var message = string. Format ("  currentthreadid Is:{0}\tappdomainid Is:{1}",
                Thread.CurrentThread.ManagedThreadId, APPDOMAIN.CURRENTDOMAIN.ID);
            Console.WriteLine (message);
            Console.read ();
        }
    
Then create a new Consoleapplication project in which a AppDomain object is created and the Example.exe program is executed through the ExecuteAssembly method in the new AppDomain. (Place files in the example-generated bin directory under the current Project Bin directory):

Class program
    {
        static void Main (string[] args)
        {
            Console.WriteLine ("Current Appdomain start!");
            ShowMessage ();
            Create a new application domain object
            AppDomain newappdomain = Appdomain.createdomain ("Newappdomain");
            newappdomain.executeassembly ("Example.exe");
            AppDomain.Unload (newappdomain);
            Console.readkey ();
        }

        The public static void ShowMessage ()
        {
            var message = string. Format ("  currentthreadid Is:{0}\tappdomainid Is:{1}",
                Thread.CurrentThread.ManagedThreadId, APPDOMAIN.CURRENTDOMAIN.ID);
            Console.WriteLine (message);
        }
    
Output:

Current Appdomain start!
Currentthreadid Is:8 AppDomainID is:1
Currentthreadid Is:8 AppDomainID Is:2

Threads with IDs equal to 8 run at AppDomain 1 and AppDomain 2 at different times.

4.3. The thread of the context:

Since threads can span appdomain boundaries, they can of course span different contexts. In the following example, the thread will run at the same time in the context of the default context and the supply thread .

Class program
    {
        static void Main (string[] args)
        {
            //Current application Domain Information
            Console.WriteLine (" Currentappdomain start! ");
            ShowMessage ();

            Runs a thread in a context-bound object
            contextbound contextbound = new Contextbound ();
            Contextbound.test ();
            Console.readkey ();
        }

        The public static void ShowMessage ()
        {
            var message = string. Format ("  currentthreadid Is:{0}\tappdomainid Is:{1}",
                Thread.CurrentThread.ManagedThreadId, Thread.CurrentContext.ContextID);
            Console.WriteLine (message);
        }

        [Synchronization]
        public class Contextbound:contextboundobject
        {public
            void Test ()
            {
                showmessage ()}
        }
    }
Output:

Currentappdomain start!
Currentthreadid is:10 AppDomainID is:0
Currentthreadid is:10 AppDomainID is:1

processes (process), threads (thread), application domain (AppDomain), contexts (context), as shown in Figure 5.0, can include multiple application domains within a process, as well as multiple threads, and threads can also travel through multiple application domains. At the same time, however, threads will only be in one application domain. Threads can also travel through multiple contexts, calling objects











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.