.NET Development Foundation/Services

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Services, threading, and application domains

Services, threading, and application domains[edit | edit source]

Exam objective: Implementing service processes, threading, and application domains in a .NET Framework application

Topics[edit | edit source]

Services[edit | edit source]

The term service stands here for a Windows service. The basic definition of a Windows service is a long-running process that does not require a user interface. Why would you need a long-running process that does not require a user interface? Essentially two reasons:

  • Doing maintenance tasks that do not need user intervention. A backup software for example will regularly check the backup schedule and execute the different backup tasks when needed. No user interface is needed for that.
  • Responding to requests that come from other processes or from the operating system. An http server such as IIS (Windows component that process web requests) will receive http requests coming from client browsers and produce responses (html pages) to those same browsers. A database process is another good example. Again the http server does not need a user interface because the interface with the client is managed by the client browser component.

The exam objectives concerning services are very basic and touch the first problems that you will encounter when dealing with them:

  • Since the service has no user interface then who will start and stop it? The answer is that the operating system executes the services directly but you have to ‘’register’’ your service to let the system know where it is and what to do with it (this is the installation process)
  • A process with a user interface essentially waits for events coming from the user. How does a service ‘’work’’ in the absence of a message pump (the technique to get user input in a typical online application)?
  • If the service does a user interface function it will “hang” waiting for a non-existent user. How can you avoid that?

The more important and complicated design issues are not covered by this exam and will be treated by the enterprise development exam.

Multithreading[edit | edit source]


To do:
Description of multithreading support in .NET

Application Domain[edit | edit source]


To do:
Short description of the application domain in the CLI

Classes, Interfaces, and tools[edit | edit source]

Implement, install, and control a service[edit | edit source]

Exam objective: Implement, install, and control a service

(Refer System.ServiceProcess namespace)

Inherit from ServiceBase class - MSDN

A service is a long-running executable. It does not provide a user interface, and does not require any user to be logged onto the computer. Services run as System, but it is possible to choose to have them run under a different user account. The ServiceBase class is a base class for a service. It must be derived from when creating a new service.
Almost all services will override the OnStart and OnStop methods of ServiceBase.

ServiceController class and ServiceControllerPermission class

ServiceController class - MSDN
ServiceControllerPermission class - MSDN

ServiceInstaller and ServiceProcessInstaller class

ServiceInstaller - MSDN
ServiceProcessInstaller class - MSDN

ServiceChangeDescription structure and ServiceChangeReason enumeration

SessionChangeDescription structure - MSDN
SessionChangeReason enumeration - MSDN

Develop multithreaded applications[edit | edit source]

Exam objective: Develop multithreaded .NET Framework applications

(Refer System.Threading namespace)

Thread class - MSDN

ThreadPool class - MSDN

ThreadStart delegate, ParameterizedThreadStart delegate, and SynchronizationContext class

ThreadStart delegate - MSDN
The simplest way to create a thread is to instantiate the Thread class. The Thread constructor takes a delegate argument. The ThreadStart delegate points to a method containing your logic. For example:
Thread t1 = new Thread (new ThreadStart(LengthyLogic));
public void LengthyLogic ()
  // Logic code
ParameterizedThreadStart delegate - MSDN
When you start a thread, sometimes you need to pass in some data for processing. .NET 2.0 provides a new delegate, ParameterizedThreadStart, which takes a parameter of type object. The class has a new overload function Thread.Start. It allows you to specify the value to be passed into the thread. This approach is simple, but is not type-safe. Example:
Thread t1 = new Thread(new ParameterizedThreadStart(LengthyLogic));
// Use the overload of the Start method that has a parameter of type Object.
static void LengthyLogic(object data)
  // Logic code
SynchronizationContext class - MSDN
The Code Project Example for SynchronizationContext Class [1]

Timeout class, Timer class, TimerCallback delegate, WaitCallback delegate, WaitHandle class, and WaitOrTimerCallback delegate

Timeout class - MSDN
Timer class - MSDN
TimerCallback delegate - MSDN
WaitCallback delegate - MSDN
WaitHandle class - MSDN
WaitOrTimerCallback delegate - MSDN

ThreadExceptionEventArgs class and ThreadExceptionEventHanlder class

ThreadExceptionEventArgs class - MSDN
ThreadExceptionEventHandler class - MSDN

ThreadState enumeration and ThreadPriority enumeration

ThreadState enumeration - MSDN
ThreadPriority enumeration - MSDN

ReaderWriterLock class - MSDN

AutoResetEvent class and ManualResetEvent class

AutoResetEvent class - MSDN
ManualResetEvent class - MSDN

IAsyncResult interface and ICancelableAsyncResult interface

(Refer System namespace)
IAsyncResult interface - MSDN
ICancelableAsyncResult interface - MSDN

EventWaitHandle class, RegisterWaitHandle class, SendOrPostCallback delegate, and IOCompletionCallback delegate

EventWaitHandle class - MSDN
RegisterWaitHandle class - MSDN
This is a typo in the exam list of objectives and the training kit. The term RegisterWaitForSingleObject should be saerch instead (see KB)
SendOrPostCallback delegate - MSDN
IOCompletionCallback delegate - MSDN

Interlocked class, NativeOverlapped structure, and Overlapped class

Interlocked class - MSDN
NativeOverlapped structure - MSDN
Overlapped class - MSDN

ExecutionContext class, HostExecutionContext class, HostExecutionContext manager, and ContextCallback delegate

ExecutionContext class - MSDN
HostExecutionContext class - MSDN
HostExecutionContext manager - MSDN
In fact was is referred to here is the HostExecutionContextManager class
ContextCallback delegate - MSDN

LockCookie structure, Monitor class, Mutex class, and Semaphore class MSDN]

LockCookie structure - MSDN
Monitor class - MSDN
Mutex class - MSDN
Semaphore class - MSDN
Lock vs Monitor vs Mutex - MSDN

Using applications domains[edit | edit source]

Exam objective: Create a unit of isolation for common language runtime in a .NET Framework application by using application domains

(Refer System namespace)

Create an application domain[edit | edit source]


An application domain is a division of a process into multiple parts. Applications running in different application domains are as isolated as they would be in different processes. So they cannot access memory in another application domain. However, if native code is run, it can gain unlimited access to the whole process, which includes other application domains.

Application domains are easier to maintain and are faster because it is easier to communicate between application domains than between processes. An application domain can hold multiple assemblies.

To create an application domain, you must at least supply a name for the new application domain:

 AppDomain ad = AppDomain.CreateDomain("Name");

Use AppDomain.CurrentDomain to get the application domain the calling thread is using.

Load assemblies into an application domain[edit | edit source]


It is possible to execute an assembly by name using AppDomain.ExecuteAssemblyByName:

 AppDomain ad = AppDomain.CreateDomain("Name");
 ad.ExecuteAssemblyByName("aname, Version=, Culture=neutral, PublicKeyToken=a9b8c7d6");

Or use AppDomain.ExecuteAssembly to supply a path to the assemby:

 AppDomain ad = AppDomain.CreateDomain("Name");
Unload an application domain[edit | edit source]


It is not possible to unload assemblies from the default application domain. However if an assembly is loaded in a different application domain, you can unload the whole application domain which includes all assemblies in that application domain.

To unload an application domain, use the static AppDomain.Unload function:

 AppDomain ad = AppDomain.CreateDomain("Name");
Configure an application domain[edit | edit source]


The most likely reason to modify the application domain configuration, is to restrict certain permissions to limit the damage if an attacker exploits vulnerabilities in an assembly.

An example is to run an assembly in the Internet Zone. The Internet Zone has limited permissions. To do this create a Zone Evidence and supply it as a parameter when creating the Application Domain:

 object [] myEvidenceTypes = {new Zone (SecurityZone.Internet)};
 Evidence myEvidence = new  Evidence(myEvidenceTypes, null);
 AppDomain ad = AppDomain.CreateDomain("Name", myEvidence); // Pass the Evidence when creating the App. Domain

It is also possible to execute only one assemby in an Application Domain with different permissions;

 object [] myEvidenceTypes = {new Zone (SecurityZone.Internet)};
 Evidence myEvidence = new  Evidence(myEvidenceTypes, null);
 AppDomain ad = AppDomain.CreateDomain("Name");
 ad.ExecuteAssembly(@"c:\path\to\file.exe", myEvidence); // Pass the Evidence in the ExecuteAssembly function

Except Evidence, you can also use the AppDomainSetup class to set other properties.

 AppDomainSetup ads = new AppDomainSetup();
 ads.ApplicationBase = @"c:\Test";
 ads.DisallowCodeDownload = true;
 AppDomain ad = AppDomain.CreateDomain("Name", null, ads); // use null as second parameter for default Evidence
Retrieve setup information from an application domain[edit | edit source]


Use the SetupInformation property of an AppDomain to read the settings from that application domain;

 AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation;

Previous / Next