Zaki Mirza’s Blog

Icon

… About software and beyond!

Intro to Application Domains

.Net framework introduces a new concept called application domains that provides code isolation within a process enviornment. These domains contain objects/assemblies/threads that can be instantiated at runtime and unloaded at runtime. This allows for a more stable application which also providing a mechanism to load/unload plugable components without having to compromise application runtime. (or the runtime host, as these kind of applications that load other applications is called).

The AppDomain class is used to create, load and work with application domains in .Net framework. I setout to work on a project that requires loading assemblies and creating local/remote objects at runtime. These objects (also called agents..yes the DistributedComuting course project) are autonomous. they just require an execution enviornment and they will work themself. They can create threads to carry out the work they are programmed to work on. A single thread at application level is supposed to deal with these agents. These can be cloned, migrated , suspended and/or destroyed.

The problem arised when loading multi-threaded agents inside my application at runtime. An agent can create multiple threads and the runtime has no information about which threads were created by which agent. Unloading the agent normally (using the dispose function which shuts off the threads this agent created smartly) is an ideal way of doing this. (since the agent itself knows the threads it has made and can dispose them). But if there is some kind of mishap during this process (or agent falls sick, or well..anything), all threads might not get destroyed. The object will be removed from the memory leaving the poor threads confused hence comes down our application crashing. There can be ways to create a single thread for an agent at my application level and make sure that all the rest of the threads are its children and die when this thread dies/suspends etc (Thats hard to achieve and a lot of code will have to be written just to tackle this problem). Also unfortunately its not possible to create a parent/child relationship between managed (or for that matter unmanged) threads. Infact Windows does not have the facility of parent/child relationship of threads(though it does for processes. The reasons are out of scope of this page. Refer to Chapter 6 of Programming Application for Microsoft Windows by Jeffery ritcher for some internals on threading under windows.) Also, considering the suspension issue of a process, since windows does not schedule processes but it schedules threads, to suspend a procesd requires suspending all the contained threads (naive approach). In our problem, we might need to suspend a single Agent (remember agents can create multiple threads). Unless we have an architecture to do so, it will be hard to know which thread is working for which agent. One way is to create a seperate process for each agent, but the overhead of creating/destroying processes, suspending processes etc is a lot under windows though in unix enviornment that might be a feasible idea. Infact thats how its carried out in a lot of of the unix applications. Again, that might create zombie issues, issues with interprocess communication etc. But that, of course is the best alternative.). Also, in a server envionrment (atleast in windows) running applications (in our case, Agents) under a single process is more scalable.

In .Net, Application Domains solves this problem (and hence this article). MSDN introduces Application Domains as follows :

“Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes. The ability to run multiple applications within a single process dramatically increases server scalability.”

Application domains are usually used by runtime hosts such as Internet explorer which load 3rd party plugins and addon applications within their process. IE creates application domains for each addon and when one fails, it (well…supposedly) does not bring down the whole process. (unless of course of the glitch happned in the IE core itself which is mostly the case).

Enough introduction to Application domains, lets come to the point. We need to create objects from the loaded assembly. These objects can create multiple threads and we need a way to isolate these threads from other objects’ threads within the same application so that they dont crash the application. Also we need to track which objects created which threads. So we create a seperate application domain for each of these objects. These application domains will serve the threads. We will load/unload these domains (consequently loading/unloading the objects and the threads they have created).

Starting off with the object itself,  I have a simple object that creates a thread and within that thread keeps printing which application domain it belongs to. (“Say my name!.. Say my name!!!….”). :p simple enough? He’re the code. Its not one of the best codes, but oh well bear with me.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ClassLibrary1
{
public class MyClass: MarshalByRefObject
{
public MyClass(){}
public void ThreadFunc()
{
while (true)
{
Thread.Sleep(500);
Console.WriteLine(Thread.GetDomain().FriendlyName);
}
}
public void MyFunc()
{
Thread t = new Thread(new ThreadStart(ThreadFunc));
t.Start();
}
}
}

We compile this code to a dll called classLibrary1.dll. Now in my application ill load this dll using reflection. ill create two application domains and create two objects of this class in both application domains, shut down one application domain and we’ll see waht happens.

using System;
using ClassLibrary1;
using System.Threading;
using System.Reflection;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
AppDomain appDomain1 = AppDomain.CreateDomain(“ad1”);
AppDomain appDomain2 = AppDomain.CreateDomain(“ad2”);

Assembly asm = Assembly.LoadFrom(“ClassLibrary1.dll”);
Type[] types = asm.GetTypes();

MyClass mc = (MyClass)appDomain1.CreateInstanceAndUnwrap(asm.FullName,types[0].FullName);
mc.MyFunc();

MyClass mc2 = (MyClass)appDomain2.CreateInstanceAndUnwrap(asm.FullName, types[1].FullName);
mc2.MyFunc();

Thread.Sleep(2000);
AppDomain.Unload(appDomain1);
Console.ReadLine();
}
}
}

As you can see, the objects created within one Application domains create threads in that application domain and do not interfere with the other application domains. This is a very* simple program to show how application domains can be created and how threads work under application domains. We can improve on this furtur by creating a dictionary of objects and their application domains to keep track of which object instance is in which application domain etc. But i guess this will get you going. Ill blog soon about how to unload  faulty objects from the application without having to screw up the application itself. :p

Advertisements

Filed under: .net, Code, , , , ,

“protected” usage

I know the title is weird, but i couldnt think of anything better. So here i was coding one of my CG assignments. It was a simple assignment though im very intrigued by game/software graphics engines so i plunged in to make my own. Its in very basic stages for now. Right now im going to talk about a problem i encountered.

Consider this, you have a class called ‘BaseObject’ which is basically for a graphical object. Now graphical objects are represented by points/vertices and how surfaces/lines are drawn between those vertices. (in my case those were indices of vertices in order. ill tell you what i mean in a sec). Now how i see it the client of the class shouldnt be allowed to create an 3d/2d object without specifing the vertices,indices and the kind of surface/line between the vertices(at the least, because otherwise it doesnt make sense for a graphical object to exists without a single vertex). The Draw() method would take care of drawing. (im using opengl as my graphics api and sdl for windowing and message handling).  So in a very usual case you’d refrain from making a default constructor of the BaseObject class and at the least it would take the array of vertices,indices and the draw method (e.g. GL_POLYGON, GL_LINES etc). So far, the code would be like this:

class BaseObject
{
public:
GLfloat* _vertices;
short _numVertices;
GLint* _indices;
short _numIndices;
GLint _drawMode;

BaseObject(
int numVertices,int numIndices,GLfloat vertices[],GLubyte indices[],GLfloat colors[],GLenum drawMode);virtual void Draw();
~BaseObject(
void);
};
 Now consider this. I want to make an specialization of this class, say a SolidCube class. So instinctivly i would inherit our SolidCube class from BaseObject class, let use tell me the center of the cube, the width,height and depth and pass that to base class which will handle the drawing. So how about:

class SolidCube : public BaseObject
{
public:
SolidCube(GLfloat width,GLfloat height,GLfloat depth,Point3D cp
);
~SolidCube();
};
Now here comes the problem. When you inherit from a class you have to initialize that in the intializer list in the constructor. Given the center point, the height, the depth and width, i know how to calculate the 8 vertices of the cube. But i have no space to do the coding between the constructor definition and the initializer of base class in initializer list. e.g.

SolidCube::SolidCube(GLfloat width,GLfloat height,GLfloat depth,Point3D cp)
: BaseObject(){}
Now we intentionally excluded that default constructor from the BaseObject definition so that noone can make an empty object. (well ofcourse they can using NULL NULL for all the arrays and all, but hey we can sort that out in some other post. this is a lame design i know). So what do we do? Well my little solution was to make use of the “protected” access modifier. It lets you secure the variable/function for the derived classes. In this case, making BaseObject’s defualt constructor protected, i make sure that the clients of the class cant use this constructor but all the derived classes can. So now the above code can work and the derived class can manually set the vertices array after working out the vertices. By the way comming back to why im using indices ill write another post on that just right now.

The visual studio will let you do something like:

BaseObject a();

and if you try to do a.Draw() or anything with “a” it will give you a compile time error. It will give you a warning though when you try to do the above thing.

Filed under: C++, Code, programming

Blog Stats

  • 104,467 landed here so far...
November 2017
M T W T F S S
« Jan    
 12345
6789101112
13141516171819
20212223242526
27282930  

tweet

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

RSS Google Shared Items

  • An error has occurred; the feed is probably down. Try again later.

RSS Google Reader Starred Items

  • An error has occurred; the feed is probably down. Try again later.

Top Clicks

  • None