All (almost all, actually) you will find here has been extracted from the MSDN. A good starting point is the section Threading Objects and Features of the .NET Framework Development Guide.
On a more operational note, see the following:
A good conceptual overview to the topic
We can divide all synchronization primitives in two classes:
This is guaranteeing mutual exclusion, only one thread (or a specific number of them) access one resource at a time.
Primitives: lock (statement), Monitor, Mutex, SpinLock, ReaderWriterLock, Semaphore
This is informing of a specific condition from one thread to another, or to several ones.
Primitives: EventWaitHandle and friends (auto reset, manual reset), Mutex, Semaphore, Barriers. All classes but Barrier derive from WaitHandle.
There are four important operations:
System.Threading.Monitor.Enter (obj); System.Threading.Monitor.Exit (obj); System.Threading.Monitor.Wait (obj); System.Threading.Monitor.Pulse (obj);
Enter and Exit lock and unlock threads calling these functions with the same object, like if the object was a semaphore or a mutex in the Phtreads library.
Wait and Pulse make possible that one thread that had acquired the monitor temporarily releases it, allowing another thread to acquire it. When that second thread acquires the monitor and calls Pulse, the first thread is scheduled to re-acquire the monitor, which may happen as soon as the second thread releases the monitor (calling Exit). Calls tu Pulse do not accumulate, that is, they are not remembered. If a thread calls Pulse and no thread is Wait-ing, the call is lost, and next time a thread calls Wait it may wait forever.
Important methods:
handle.WaitOne () System.Threading.WaitHandle.WaitAll (WaitHandle []) System.Threading.WaitHandle.WaitAny (WaitHandle [])
Derived classes differ in thread affinity (who can signal/release the wait handle, the thread that got it, or anyone?); mutexes have thread affinity, others have not
All the three classes inherit from WaitHandle. We focus on EventWaitHandle, as the behaviour of AutoResetEvent and ManualResetEvent can be explained in terms of EventWaitHandle.
We can create an EventWaitHandle as follows:
h = new EventWaitHandle (false or true, EventResetMode.AutoReset or EventResetMode.ManualReset);
AutoResetEvent and ManualResetEvent are classes deriving from EventWaitHandle and behave like the latter one, as if the instance of EventWaitHandle had been constructing passing the appropriate value to the second parameter of the constructor
Consider the following code:
CountdownEvent cde = new CountdownEvent (12)
See this article on the development guide.
As before, he will heaviliy rely on the section Network Programming in the .NET Framework of the .NET Framework Development Guide.
Namespace System.Net.Sockets.
We focus on connective sockets, using TCP. The first step is creating the socket.
While the client usually only establishes one connection at a time, the server needs to deal with potentially several ones. As in probably any other language you know, we have a select function for checking the status of several threads and blocking until we need to do some work.
The static method Socket.Select takes three lists of (references to) Socket instances and can block until there is something to read (first list), something to write (second list) or an error was reported (third list). A call to Select will return when at least one socket is ready to do work with it, which we can check with the Poll method of the Socket class.
If a socket is a listening socket, i.e., it is being used to accept new clients, place it in the reading list. If a client has arrived, and Accept will return immediately with its associated Socket, then the Poll method will return true when invoked with the SelectMode.SelectRead switch.
The classes TcpClient, TcpListener, and UdpClient help you opening data connections over TCP and UDP, as well as accepting incoming TCP connections. They abstract away the details of setting up and using sockets and provide a simplified access to the network.
Their use is straightforward, see
The Windows registry is a database where applications can store settings, configuration, and in general information that shall be preserved after the application is closed.
It offers an interface to store and retrieve information with a tree-like structure, where each branch of the tree is technically called a key and each node of the tree can store zero or more pairs of the form
(name, value)
For instance, the well known application Notepad seems to store some settings under the key
KEY_CURRENT_USER\Software\Microsoft\Notepad
where we find a number of name-value pairs storing certain settings, such as:
("IfFaceName", "Fixedsys") ("iWindowPosX", 0x00000012) ("iWindowPosY", 0x0000002f)
You can visualize (and modify!) the Windows registry using the tool regedit.exe (you may want to type the name of the program at the Start > Execute dialog).
In .NET, the two main classes to access the registry are the Registry class and the RegistryKey class, both located within the namespace Microsoft.Win32.
Important entry points to the MSDN documentation:
Two examples:
object obj; obj = Registry.GetValue("HKEY_CURRENT_USER\\Software\\WinRAR\\ArcHistory", "1", null); RegistryKey k; k = Registry.CurrentUser; Console.WriteLine (k); Console.WriteLine (k.Name); Console.WriteLine (k.ValueCount); Console.WriteLine (k.SubKeyCount); foreach (var s in k.GetValueNames()) Console.WriteLine(s); foreach (var s in k.GetSubKeyNames()) Console.WriteLine(s);
There are several standard entry points to the registry, they correspond to the nodes of the tree hanging just below the root of the tree (see the static fields of class Registry).
Also, each value in a name-value pair has a type associated to it (see the method Registry.SetValue and the enumeration RegistryValueKind).
The Windows event log is a place where both Windows and applications running on top of it record important software and hardware events. Each entry in the log contains informations such as the machine where it was generated, the generation time, a source, and of course a text message.
The source identifies, conceptually, the application originating the event, although a source does not need to designate an application. Both the log where the event will be stored as well as the source need to be created within the system well before events can be logged.
Several standard event logs are already present in the machine. In particular, the log Application will be of interest for us. You can view the contents of existing event logs using the Event Viewer (Start > Control Panel > System and Security > Administrative Tools > Event Viewer, administrative permission will be required). Many informations about the existing event logs are stored at the registry, see here.
It is possible to create new event logs and sources. This should be done well before you start using the log, as Windows apparently needs some time to update its files (...). Ideally this should be done during the installation of your application.
In .NET, we can
A Windows service is a notion analog to that of a daemon in Unix: a long-running process, executing in background, and offering some service to someone else. See this introduction to service applications from the MSDN library.
Unlike a Unix daemon, which often only offers one service, a single Windows program can contain several Windows services. They must be installed on the server before they run. That is, we need to carry out some specific procedure by which the Service Control Manager (SCM) will get to know the executable binary where our services are contained and the services themselves. Once this is done, we will be able to start, stop, or pause the service from the SCM.
Services, thus, function differently from regular applications. The overall procedure to write and run a service coded in .NET is as follows:
Here you have a minimal example (warning, I didn't compile it!):
using System.ServiceProcess; using System.Configuration.Install; static class Program { static void Main() { ServiceBase.Run (new PingService ()); } } public class PingService : ServiceBase { public PingService() { ServiceName = "PingService"; CanPauseAndContinue = true; } protected override void OnStart(string[] args) { // do something } protected override void OnStop() { // do something } protected override void OnPause() { // do something } protected override void OnContinue() { // do something } } /* for the install utility to recognize Setup as a valid installer */ [RunInstaller(true)] public class Setup : System.Configuration.Install.Installer { private ServiceProcessInstaller proc_inst; private ServiceInstaller serv_inst; public Setup() { proc_inst = new ServiceProcessInstaller(); serv_inst = new ServiceInstaller(); proc_inst.Account = ServiceAccount.LocalSystem; proc_inst.Password = null; proc_inst.Username = null; serv_inst.Description = "A long description of your service"; serv_inst.DisplayName = "The name you will see in the SCM"; serv_inst.ServiceName = "PingService"; serv_inst.StartType = ServiceStartMode.Automatic; Installers.Add (proc_inst); Installers.Add (serv_inst); } }
Several good entry points to the subject on the MSDN library:
Finally, to start the service, open the SCM (Start > Programs > Administrative Tools > Services), search for your service (the column "Name" is the DisplayName property of the ServiceInstaller object created during installation) and click on Start, Stop (or Pause). You can also manually do it from code, using the ServiceController class.