Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of AppDomain in C#

What is the most important use of AppDomains in C#?

like image 791
Nipun Avatar asked Mar 20 '09 10:03

Nipun


People also ask

What is AppDomain used for?

The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown.

How does an AppDomain get created?

AppDomains are created by the . Net runtime when a managed application is initialised. When you start ABC. EXE, it gets an application domain.

What is the difference between AppDomain assembly process and a thread?

A process is an executing application (waaaay oversimplified). A thread is an execution context. The operating system executes code within a thread. The operating system switches between threads, allowing each to execute in turn, thus giving the impression that multiple applications are running at the same time.

What does AppDomain CurrentDomain BaseDirectory return?

AppDomain.CurrentDomain.BaseDirectoryThis path gives you the path of the Entrypoint of the application or from where the Current AppDomain is created. For instance, say your executable is executed on assembly a.exe, but the code is written in b.


2 Answers

The single most important use is that your code has to have one - i.e. everything you write in C# executes in an AppDomain. That is quite important ;-p

If you mean additional app-domains:

When using plugins and other untrusted code, it allows you both isolation, and the ability to unload them (you can't unload assemblies - only entire app-domains).

I'm using it currently to load dynamically generated dlls, so that I can unload them.

They also allow you to set different configuration files, trust levels, etc - but have associated costs of complexity and remoting.

MSDN has a section on app-domains, here.

like image 127
Marc Gravell Avatar answered Oct 02 '22 19:10

Marc Gravell


I can't tell you what the most important use is, since that depends on the situation.

AppDomains are useful for sandboxing parts of your application. You can load extensions in an AppDomain and unload them again - something you cannot otherwise do. You can assign specific rights to AppDomains. Per default objects in different AppDomains cannot access each other.

AppDomains can be viewed as lightweight processes as they give you many of the same features. However, unlike a Process new AppDomains do not have their own thread per default. You have to manage AppDomains and threads yourself.

Also, AppDomains all share the same managed heap. This is usually not a problem, but it may have surprising effects as some instances like strings are shared among AppDomains. For regular use this is not an issue, but if you use strings for locking, threads in different AppDomain can affect each other.

like image 35
Brian Rasmussen Avatar answered Oct 02 '22 19:10

Brian Rasmussen