"Plug-in Framework exploration series" Application domain (AppDomain)

Source: Internet
Author: User

The application domain (AppDomain) is not a new term, as long as the familiar. NET knows its existence, but let's first come back to know the application domain, it is what is sacred.

application domain

As we all know, the process is the smallest unit of code execution and resource allocation, each process has its own unit of memory, and the processes are isolated from each other, and naturally, the process becomes the security boundary for code execution.

A process that corresponds to an application is a common perception, While. NET breaks this practice, because it brings the new concept of application domains, the CLR can use application domains to provide isolation between applications, and in one process multiple application domains can run, meaning that we can run multiple applications in one process with application domains, without causing inter-process calls or processes Additional overhead of switching between the two.

Do you think the application domain is a very magical thing, don't worry, we will look at its isolation characteristics and bring us what.

Advantage

First, there is no interaction between application domains, it is a natural anomaly isolation mechanism. That is, errors that occur in one application domain do not affect other application domains because type-safe code does not cause memory errors.

Second, it can dynamically load and unload assemblies at run time. As we all know, in the. NET world, once the loader loads the assembly, it will always exist throughout the life of the application, and the application domain changes it, providing us with the ability to unload the assembly.

Finally, the application domain can implement security policies and configuration policies separately. Frankly, you can configure the appropriate permissions for each application domain to better manage the application.

It's also worth noting that there is no one-to-one correlation between application domains and threads. At any given time, multiple threads can be executed in a single application domain, and a particular thread is not confined to a single application domain. That is, threads are free to cross application domain boundaries, and if there is no active city thread, then multiple application domains are still running in the same thread.

In general, application domains form the isolation, uninstallation, and security boundaries of managed code. And these features bring to a plug-in framework will be abnormal isolation, dynamic loading of the unload plug-in and a more secure plug-in operating environment.

Since this article is intended to be based on the nature of the application domain for framework design, let's assume that you have a certain understanding of the application domain, and here's an example that lets us take a step-by-step look at these characteristics of the application domain.

Creating and uninstalling an AppDomain

Using C # We can create an application domain in the following way and execute a piece of code in the new domain:

AppDomain domain = Appdomain.createdomain ("Hello appdomain!");

Domain. DoCallback (new crossappdomaindelegate () =

{

Window win = new window

{

Width = 300,

Height = 100,

Content = AppDomain.CurrentDomain.FriendlyName

};

Win. Show ();

}));

After running, you can see that the window created in the new domain is displayed as follows:

Uninstalling an application domain can be done through the AppDomain static method AppDomain.Unload (domain), which is simple.

Configure how domain is loaded

If you run the above code, it is not found that the new domain created window after a long time to present, this is how it is, simply speaking, This is because the default behavior of the. NET loader is that the referenced assemblies are reloaded in each domain (including the framework itself, except for mscorlib), and of course we can change this behavior, but before we get to the next new concept, "domain Neutrality ", details can be seen in this article domain Neutral assemblies, simply speaking it has the ability to share assemblies across domains, which avoids the loss of repeated loading, We can modify the default load mode by adding the loaderoptimization tag to the program entry main function:

[System.STAThreadAttribute ()]

[System.Diagnostics.DebuggerNonUserCodeAttribute ()]

[Loaderoptimization (

Loaderoptimization.multidomainhost)]

public static void Main ()

{

Appdomaintest.app App = new Appdomaintest.app ();

App. InitializeComponent ();

App. Run ();

}

Recompile and run, the speed has a significant increase in it.

Loaderoptimization There are three ways (Singledomain, MultiDomain and multidomainhost), in domain Neutral Assemblies in a detailed interpretation, interested friends can see, here will not repeat.

Exception Isolation  

For a plug-in framework, exception isolation is important, which is a necessary feature to ensure the stability of a framework. Let's look at how to implement exception isolation using application domains.

Let's start by simulating throwing exceptions in the newly created domain:

AppDomain domain = Appdomain.createdomain ("Hello appdomain!");

Domain. DoCallback (new crossappdomaindelegate () =

{

Window win = new window

{

Width = 300,

Height = 100,

Content = AppDomain.CurrentDomain.FriendlyName

};

Win. Loaded + = (obj, arg) = =

{

throw new Exception ("Test Exception.");

};

Win. Show ();

}));

This is used in the window loaded event to directly throw an exception to achieve the simulation effect, OK, compile and run, unfortunately, the success of hanging off.

This is because the unhandled exception in the new domain will eventually be thrown into the default domain, resulting in a crash. To verify this, it's easy to just add the AppDomain.CurrentDomain.UnhandledException event handler in the default domain to intercept the exception thrown in the new domain, but here you can only intercept but not change the result of the crash.

So how can you handle this exception, registering System.Windows.Threading.Dispatcher.CurrentDispatcher.UnhandledException event handling in the default domain or the new domain, as shown in the following example:

AppDomain domain = Appdomain.createdomain ("Hello appdomain!");
System.Windows.Threading.Dispatcher.CurrentDispatcher.UnhandledException + = (obj, arg) = =
{
Arg. Handled = true;
MessageBox.Show (Arg. Exception.Message);
AppDomain.Unload (domain);
};
Domain. DoCallback (new crossappdomaindelegate () =
{
Window win = new window
{
Width = 300,
Height = 100,
Content = AppDomain.CurrentDomain.FriendlyName
};
Win. Loaded + = (obj, arg) = =
{
throw new Exception ("Test Exception.");
};
Win. Show ();
}));

Note the most critical arg. Handled = True this sentence, its meaning is to tell the system this event has been processed, do not pass down, and finally take the initiative to uninstall the new domain, and the default domain is still running normally, so that the effect of abnormal isolation.

combining plug-ins in different domains  

Assuming all the plugins are in different domains, how do you combine them, that is, how to present the plug-ins in different domains to a single container.

As we all know, to implement objects passing between domains, the object must be serializable or inherit from the MarshalByRefObject type, but the UI control is powerless, this need Microsoft's AddIn framework to help, although we all feel that the AddIn framework is complex, difficult to use, But there are many things that are useful, such as the Frameworkelementadapters class that will be used here, It provides two static methods Contracttoviewadapter and Viewtocontractadapter are used to achieve mutual conversion between FrameworkElement and INativeHandleContract, Legend has it that this conversion is done through a handle. Or an example of how to make a plugin cross-domain rendering, first add System.Addin.Contract.dll and System.Windows.Presentation.dll two references, and then write the following code

AppDomain domain = appdomain.createdomain ("test");
Domain. DoCallback (new crossappdomaindelegate () =
{
To create a button control in a new domain
Button btn = New Button {Content = "Test"};
To convert a button control to INativeHandleContract
INativeHandleContract ICT = frameworkelementadapters.viewtocontractadapter (BTN);
AppDomain.CurrentDomain.SetData ("Testbtn", ICT);
}));
Get the INativeHandleContract object in the new domain in the primary domain
INativeHandleContract iContract = domain. GetData ("Testbtn") as INativeHandleContract;
Convert INativeHandleContract objects back to FrameworkElement
FrameworkElement Ctrl = Frameworkelementadapters.contracttoviewadapter (IContract);
Application.Current.MainWindow.Content = CTRL;

The results of the operation are as follows, and the controls created in the new domain are successfully rendered in the primary domain

As for the Permissions configuration section in the domain, it will be described in the next article.

Plug-in Framework Exploration series application domain (AppDomain)

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.