Tuesday, March 10, 2009

Windows Communication Foundation FAQ quick starter

http://www.codeproject.com/KB/aspnet/WCF.aspx

Title: Windows Communication Foundation FAQ quick starter
Author: Shivprasad Koirala

Email: shiv_koirala@yahoo.com
Language: C#
Level: Beginner
Description: Windows Communication Foundation FAQ quick starter

Update :- With links of WCF-Part 2, WPF and WWF.


Windows Communication Foundation FAQ quick starter


Introduction

What is .NET 3.0?

What is Windows Card Space?

What is WCF?

What are the important principles of SOA (Service oriented Architecture)?

What are ends, contract, address, and bindings?

Which specifications does WCF follow?

What are the main components of WCF?

Explain how Ends, Contract, Address, and Bindings are done in WCF?

what is a service class?

what is a service contract, operation contract and Data Contract?

what are the various ways of hosting a WCF service?

How do we host a WCF service in IIS?

what are the advantages of hosting WCF Services in IIS as compared to self-hosting?

what are the major differences between services and Web services?

What is the difference WCF and Web services?

What are different bindings supported by WCF?

Which are the various programming approaches for WCF?

What is one-way operation?

Introduction


In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF.
In case you like the article or your think I need improvements please send me a message at http://www.questpond.com . I am sure every one needs improvements.
Enjoy…

Click here to see Windows Communication Framework (WCF) - Part 2

Click here to see Windows Presentation Foundation (WPF)

Click here to see Windows Workflow Foundation (WWF)

What is .NET 3.0?


In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Windows Workflow Foundation + Windows Card Space.

What is Windows Card Space?


It was previously known by its codename Info Card. It is a framework by Microsoft, which securely stores digital identities of a user and provides a unified interface to choose the identity for a particular transaction, such as logging in to a website. Windows Card Space is a central part of Microsoft’s effort to create an identity met system, or a unified, secure and interoperable identity layer for the internet.

What is WCF?


First let us give a short answer to this: - “WCF (Indigo was the code name for WCF) is a unification of .NET framework communication technologies “.WCF is a unification technology, which unites the following technologies:-
• NET remoting
• MSMQ
• Web services
• COM+.
Below figure depicts WCF fundamentals pictorially.

Figure: 1 - WCF Components


What are the important principles of SOA (Service oriented Architecture)?


WCF is based on SOA. All big companies are playing big bets on SOA. So how can Microsoft remain behind? So in order to implement SOA architecture easily you need to use WCF.
SOA is based on four important concepts:-

• Boundaries are well defined


In SOA, everything is formalized. The client who is consuming the service does not need to know how the implementation of the service is done. If you look at some old methodologies of communication like DCOM. Any changes at server level the client also has to change. Therefore, the server and client implementation was so much bound that changes need to be done at all places. In SOA, the rule is if you do enhancement you do not need to change anything at the client. SOA based application only understands that there is an end point, contract, and bindings.

Note: - Just to clarify shortly about end point and contract. Any SOA service is exposed through an end point. End point defines three important aspects What, Where and How. We will understand more details of the same in the later questions.


• Services evolve


Change is the law of nature and services will evolve. In SOA, services can be versioned and you can host those services in new ends. For instance, you have a service called as “Search Tickets (Ticket Number) “which gives details based on Ticket Number and its exposed on end point “ep1”. Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end “ep2” with service “Search Tickets (Ticket Number, Passenger Name)”. So the client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.

• Services share only schemas and contracts


Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is not heavy coupling between environments.

• Service compatibility is policy based


Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of client one which uses Remoting as the communication methodology while other client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies.

Note: - Many people assume Web services are the base for SOA. The answer is 50 % right. What web services lack is the policy based Service compatibility. If you host a web service it can only serve with HTTP communication channel and SOAP message. Any other type of client trying to communicate he will not degrade it self. This is what is provided by WCF. You can host the service in one or more mode. For instance you can host a WCF service using remoting and ASMX.

What are ends, contract, address, and bindings?


The above terminologies are the core on which SOA stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-

• Contract (What)


Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.

• Address (Where)


An Address indicates where we can find this service. Address is a URL, which points to the location of the service.

• Binding (How)


Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.
Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.

Figure 2: - Endpoint Architecture


Note: - You can also remember the end point by ABC where A stands for Address, B for bindings and C for Contract.

Which specifications does WCF follow?


WCF supports specifications defined by WS-* specifications. WS-* specifications are defined together by Microsoft, IBM, SUN and many other big companies so that they can expose there service through a common protocol. WCF supports all specifications defined we will understand them one by one.

• Messaging (WS-Addressing):-
SOAP is the fundamental protocol for web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML optimized packaging (XOP). Because the data will sent in binary and optimized format, it will give us huge performance gain.

• Security (WS-Security, WS-Trust, and WS-Secure Conversation):-
All the three WS- define authentication, security, data integrity and
privacy features for a service.
• Reliability (WS-Reliable Messaging):- This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times.

• Transactions (WS-Coordination and WS-Atomic Transaction):- These two specifications enable transaction with SOAP messages.

• Metadata (WS-Policy and WS-Metadata exchange):- WSDL is a implementation of WS-Metadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL.
We have stressed on the WS-* specification as it is a specification which a service has to follow to be compatible with other languages. Because WCF follows WS-* specifications other languages like JAVA , C++ can also exploit features like Messaging , Security , Reliability and transactions written in C# or VB.NET. This is the biggest achievement of WCF to integrate the above features with other languages.

Note: - During interview the interviewer expects that you know what WS-* specification are supported by WCF and its advantages with respect to interacting with other languages.


What are the main components of WCF?


We need to define three main components in WCF:-
• Service class.
• Hosting environment
• End point

Explain how Ends, Contract, Address, and Bindings are done in WCF?


what is a service class?


what is a service contract, operation contract and Data Contract?


In this example, we will make simple service, which displays the total cost of the complete product group. In simple words, this service will take three parameters per product cost, number of products and the product name. In return the service will return the total cost of all the products by multiplying number of products * cost per product. As we go ahead in this explanation, we will try to understand all the terminologies, which are asked in the above question.
First, you need to create a Winfx service project. You can see in the below figure we have selected the Winfx project.

Figure 3: - Create new WinFX Service class


In this project, we add a new class and name it as “serviceGetCost.cs”. This class will have our core implementation and this is the class, which has all the action. The service class, which has to be exposed to the external client. We need to use the Service Contract attribute to mark it as a service class.
Service Contract attribute define saying which application interface will be exposed as a service.
You can see in the below code snippet we have made an interface and marked it as Service Contract. It is not essential that you need to use an interface you can also use a simple class and mark it as Service but interface represent a contract and do not have implementation. In short, they stand at a very higher level of abstraction. So as a good design practice-using interface to represent a service contract makes more sense.
The next thing to note is the Operation Contract attribute.
Operation Contract dictates which methods should be exposed to the external client using this service.
It defines individual exchange or request and replies. In the current sample, we have defined GetTotalCost method, which will be used by the end client to get the total cost results.
The next thing to note in the code snippet is the Data Contract attribute. In the previous two steps, we have exposed class as a service by using Service Contract and methods by using Operation Contract. Every operation will definitely do some kind of data transfer.
Data Contract attributes defines which type of complex data will be exchanged between the client and the service. They determine which parameters to be serialized.
When you are using simple data types like int, bolo etc it is not necessary that you need to mark the data contract attribute. Because you will always find matching types on the client. However, complex structure like one shown in the below code snippet you will need to define a data contract. Remember data contract define how this data will be passed during transmission. In short data contract attribute define how data will be serialized will transmission.
In the below sample we have marked the structure product data to be serialized.

Figure 4:- The Service class


As data contract are all about serialization you need to import System.Runtime.Serialization name space.
In the next step, we implement the GetTotalCost function. It just returns a simple string with product name and the total cost of all products.
Once our service class is done its time to host this service. There are various ways of hosting a WCF service we will look in to the same in the next question. For the current example, we will host in their own process.

Figure 5: - Hosting the service


Hosting the WCF service needs two things one is the config file and second is the hosting code on startup. Because we are hosting this service in its own application process this needs to be a windows application. So first let us have a look what entries do, we need to make in the App.config file. In the above figure, everything is clear but let us understands all the section defined in the App.config file.
In the configuration section, we need to add a new section . The most important part of is the endpoint tag. As said in the previous answer End gives three important answers Where, What and How. In short where is the service, what the contract of the service is and how do we communicate with the service.
In the above code snippet, we have only defined the contract i.e. what and how that is bindings. The where is defined in the application entry point static void main ().
Therefore, the contract attribute defines the interface and binding says that the end clients can communicate using “HTTP” protocol.
In Static void Main method, we create an object of Service Host class and use the open method to host the service. We have used the URI object to define the address where the service will be hosted.

Figure 6: - Service Started


If you compile the project, you will see something as shown in the above figure. This says that the service is up and running and ready to serve any WCF client. Now its time to develop consumer, which will consume this WCF service. Microsoft has provided a decent automation to generate the client. Therefore, below figure depicts the various steps.

Figure 7: - svcutil in action


Go to command prompt of windows SDK and run the following command:-
Svcutil
In the above command is the URI on which the service is hosted. One you run the command against the URI it will generate two files one is the config file and the other is the proxy. You can see in the above figure two files are generated serviceGetCost.cs and output.config file. With the help of these two files, we will make our client.

Figure 8: - Client code walkthrough


You can see in the above figure we have made WFCClientGetCost project. In that, we have added output.config and serviceGetCost.cs to the client project. We have renamed output.config to app.config.
Once we have done with everything, its time to write the client code, which calls the proxy who in turn will call the service hosted. In the above figure, you can see we have the client code also. It is a simple code we first created the object of the data structure set the values. Then we create the object of the service and call the GetTotalCost function.
If everything is compiled and you run the server and client, you should get your output as shown below.

Figure 9: - Output of WCF service


what are the various ways of hosting a WCF service?


There are three major ways to host a WCF service:-
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation Service) Server.

How do we host a WCF service in IIS?


Note: - The best to know how to host a WCF in IIS is by doing a small sample. So what we will do is host the same GetCost sample which was self hosted in the previous question.


First thing you will need is to create the SVC file, which exposes the service class. SVC file contains the pointer to the class. You can see from the figure below the class attribute points to the class whose interface is exposed by the service.svc.cs file. Also, note the actual interface is in service.svc.cs file. Below figure, have both the files service.svc, which has the class attribute which points to the service class, and the interface, which resides in service.svc.cs file. We have taken the same sample, which was self-hosted in the previous question.

Figure 10: - The SVC file and the behind code


We also need to provide implementation for the interface. So we have made a class ServiceGetCost which has the actual implementation. Below figure shows the same in detail. In the below figure you can also see the solution files.

Figure 11: - Implementation of Service.svc.cs


We also need to specify the service type and endpoint in web.config file. Also, note we have specified HTTP binding because we will be hosting the service on IIS.

Figure 12: - Web.config file for hosting service on IIS


Now that we are done with the coding part. We need to create the virtual directory in IIS. In the below figure in Step1 and Step2 we have shown how to create the virtual directory in IIS. One important thing to note while creating virtual directory set the access permission to execute.

Figure 13:- IIS Configuration


In the third step, we will publish the website to our virtual directory. Note the fourth step in which we have copied the svc file so that the service can be requested.
Note: - ASP.NET compilation has changed in ASP.NET 2.0. In 2.0 there is no concept of solution files. So if you want to have full compiled DLL you need to publish the project to a virtual directory.
Once you have hosted the SVC file you can test the same by request the service.svc file. If everything works fine you will get something as shown in the below figure

Figure 14:- IIS WCF client


Using the Svcutil.exe, you will need to generate the proxy class and the config file. The proxy and config will be same, as we had done for self-hosting. The one important change is the address. The config file URL now points to the service.svc, which is hosted on IIS. You can run the same client, which we had created for self-hosting. The only change you will need to do is change the endpoint address.

Figure 15:- Output of WCF client at IIS


LOL…You should get the same output, which we had received, for self-hosting.

what are the advantages of hosting WCF Services in IIS as compared to self-hosting?


There are two main advantages of using IIS over self-hosting:-

Automatic activation


IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self hosting the service should always be running.

Process recycling


If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you loose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
In case of self-hosting both the above features, you will need to code yourself. Lot of work right!!. That is why IIS is the best option for hosting services until you are really doing something custom.
Below figure shows where the recycle option is located in IIS. You need to click on the DefaultAppool and then Properties.

Figure 16:- IIS recycle option


what are the major differences between services and Web services?


What is the difference WCF and Web services?


Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

What are different bindings supported by WCF?


WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just incase you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides.
BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.

Note: - MTOM is discussed in one of the pervious questions in this chapter.


WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.
NetTcpBinding: - This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be also made in .NET language.
NetNamedPipesBinding:-Ths binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.

Note: - An interprocess control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.


NetMsmqBinding: - This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.

Which are the various programming approaches for WCF?


What is one-way operation?

IsOneWay equal to true ensures that the client does not have to wait for the response. So methods marked by IsOneWay to true should always return void. In this, the caller does not get anything in return so it is called as one-way communication.
In order to understand one-way implementation in WCF lets make a code walkthrough of a sample.
Note: - You can find code for the same in “WCFIsOneWay” folder in CD.

Figure 17: - One-Way in action


Above is the code snippet, which describes practically how one way works in WCF. The above given code snippet is numbered. Below is the explanation according to the numbers marked in figure:-
1 - This is the code snippet of the server service. We have created a method called as doHugeTask. DoHugeTask makes the method sleep for 5000 MS and then displays the time when the task is completed.
2 - This code snippet is for client. It creates a proxy object of serviceIsOneWay and calls the doHugeTask method. After calling the doHugeTask, the client execution continues ahead. So as a proof, we display the time when the method calling was completed.
3 - This screen shot shows the output given by both server and client. The top window displays the server output and the below windows displays the client output.

Note: - You can find the code for the same in WCFIsOneWay folder. For generating the proxies you have to follow the same steps which are shown in the previous steps.

So run the server program first i.e. ServiceIsOneWay and run the client later. You will see the client runs the doHugeTask and moves ahead. Therefore, the client completion time is less than the server is. One more thing to understand is that one way does not give any notification back of completion. Therefore, it is like fire and forgets.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Threading - Q&A lots of Java

Threading

1.What’s difference between thread and process?

A single process can have multiple threads that share global data and address space with other threads running in the same process, and therefore can operate on the same data set easily. Processes do not share address space and a different mechanism must be used if they are to share data.
If we consider running a word processing program to be a process, then the auto-save and spell check features that occur in the background are different threads of that process which are all operating on the same data set (your document).

--
process is a execution of a program and program contain set
of instructions but thread is a single sequence stream
within the process.thread is sometime called lightweight
process. single thread alows a os to perform singler task

ata time similarities between process and threads are:
1)share cpu.
2)sequential execution
3)create child
4)if one thread is blocked then the next will be start to
run like process.
dissimilarities:

1)threads are not independent like process.
2)all threads can access every address in the task unlike
process.
3)threads are design to assist onr another and process
might or not might be assisted on one another.


2. What is thread safety and synchronization?

By far, the most common use of thread synchronization is to ensure mutually exclusive access to a shared resource by multiple threads. In the Win32® API, the CRITICAL_SECTION structure and associated functions offers the fastest and most efficient way to synchronize threads for mutually exclusive access when the threads are all running in a single process. The Microsoft® .NET Framework doesn't expose a CRITICAL_SECTION structure, but it does offer a similar mechanism allowing mutually exclusive access among a set of threads running in the same process. This mechanism is made possible by way of SyncBlocks and the System.Threading.Monitor class.

class SomeType {
private:
// The private CRITICAL_SECTION field
// associated with each object

CRITICAL_SECTION m_csObject;

public:
SomeType() {
// The constructor initializes the
// object's CRITICAL_SECTION field
InitializeCriticalSection(&m_csObject);
}


~SomeType() {
// The destructor deletes the
// object's CRITICAL_SECTION field
DeleteCriticalSection(&m_csObject);
}

void SomeMethod() {
// In the methods, we use the object's

// CRITICAL_SECTION field to synchronize
// access to the object by multiple threads.

EnterCriticalSection(&m_csObject);
// Execute thread-safe code here...
LeaveCriticalSection(&m_csObject);

}

void AnotherMethod() {
// In the methods, we use the object's
// CRITICAL_SECTION field to synchronize
// access to the object by multiple threads.

EnterCriticalSection(&m_csObject);

// Execute thread-safe code here...
LeaveCriticalSection(&m_csObject);
}
};

class Transaction {


// Private field holding the time of
// the last transaction performed
private DateTime timeOfLastTransaction;

public void PerformTransaction() {
// Lock this object
Monitor.Enter(this);


// Perform the transaction...

// Record time of the most recent transaction
timeOfLastTransaction = DateTime.Now;

// Unlock this object
Monitor.Exit(this);
}


// Public read-only property returning
// the time of the last transaction
public DateTime LastTransaction {
get {
// Lock this object
Monitor.Enter(this);

// Save the time of the last transaction

// in a temporary variable
DateTime dt = timeOfLastTransaction;

// Unlock this object
Monitor.Exit(this);

// Return the value in the temporary variable
return(dt);

}
}
}

class Transaction {

// Private field holding the time of
// the last transaction performed

private DateTime timeOfLastTransaction;

public void PerformTransaction() {
lock (this) {
// Perform the transaction...

// Record time of the most recent transaction
timeOfLastTransaction = DateTime.Now;

}
}

// Public read-only property returning
// the time of the last transaction
public DateTime LastTransaction {
get {
lock (this) {
// Return the time of the last transaction

return timeOfLastTransaction;
}
}
}
}

What is semaphore?

A hardware or software flag.
In multitasking systems, a semaphore is a variable with a value that indicates the status of a common resource.
Its used to lock the resource that is being used.
A process needing the resource checks the semaphore to determine the resource's status
and then decides how to proceed.

In programming, especially in UNIX systems, semaphores are a technique for coordinating or synchronizing activities
in which multiple process compete for the same operating system resources.
A semaphore is a value in a designated place in operating system (or kernel) storage that each process can check and then change.
Depending on the value that is found, the process can use the resource or will find that it is already in use and must wait for some period before trying again.
Semaphones can be binary (0 or 1) or can have additional values.
Typically, a process using semaphores checks the value and then, if it using the resource, changes the value to reflect this so that subsequent semaphore users will know to wait.
Semaphores are commonly use for two purposes: to share a common memory space and to share access to files.
Semaphores are one of the techniques for interprocess communication (interprocess communication).
The C programming language provides a set of interfaces or "functions" for managing semaphores.



What are monitors?


Monitors

Like the lock keyword, monitors prevent blocks of code from simultaneous execution by multiple threads. The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit. This is just like using the lock keyword. In fact, the lock keyword is implemented with the Monitor class. For example:

lock (x)
{
DoSomething();
}

This is equivalent to:

System.Object obj = (System.Object)x;
System.Threading.Monitor.Enter(obj);
try

{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(obj);
}

Using the lock keyword is generally preferred over using the Monitor class directly, both because lock is more concise, and because lock insures that the underlying monitor is released, even if the protected code throws an exception. This is accomplished with the finally keyword, which executes its associated code block regardless of whether an exception is thrown.

For more information on monitors, see Monitor Synchronization Technology Sample.



What’s the importance of synchronized blocks?
http://stackoverflow.com/questions/574240/synchronized-block-vs-synchronized-method

The only real difference is that a synchronized block can choose which object it synchronizes on. A synchronized method can only use 'this' (or the corresponding Class instance for a synchronized class method). For example, these are semantically equivalent:

synchronized void foo() {

...
}

void foo() {

synchronized (this) {

...
}
}

The latter is more flexible since it can compete for the associated lock of any object, often a member variable. It's also more granular because you could have concurrent code executing before and after the block but still within the method. Of course, you could just as easily use a synchronized method by refactoring the concurrent code into separate non-synchronized methods. Use whichever makes the code more comprehensible.



How do we create threads?

win32 api function CreateThread()
Thread

what’s the difference in using runnable and extends in threads?
JAVA
http://www.particle.kth.se/~lindsey/JavaCourse/Lectures/Lecture_7A/threads.html



Can you explain Thread.sleep?

According to the docs, calling Thread.Sleep(0) causes the thread to be
"suspended to allow other waiting threads to execute."


How to stop a thread?
Abort or let it run to stop itself

What is wait() and notify() ?

Can you explain how Scheduling and Priority works in threads?
Can you explain Yielding in threading?
what are daemon threads?

Thread Synchronization (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/ms173179.aspx

Thread Synchronization (C# Programming Guide)

The following sections describe features and classes that can be used to synchronize access to resources in multithreaded applications.

One of the benefits of using multiple threads in an application is that each thread executes asynchronously. For Windows applications, this allows time-consuming tasks to be performed in the background while the application window and controls remain responsive. For server applications, multithreading provides the ability to handle each incoming request with a different thread. Otherwise, each new request would not get serviced until the previous request had been fully satisfied.

However, the asynchronous nature of threads means that access to resources such as file handles, network connections, and memory must be coordinated. Otherwise, two or more threads could access the same resource at the same time, each unaware of the other's actions. The result is unpredictable data corruption.

For simple operations on integral numeric data types, synchronizing threads can be accomplished with members of the Interlocked class. For all other data types and non thread-safe resources, multithreading can only be safely performed using the constructs in this topic.

For background information on multithreaded programming, see:

The lock Keyword

The lock keyword can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.

A lock statement begins with the keyword lock, which is given an object as an argument, and followed by a code block that is to be executed by only one thread at a time. For example:

public class TestThreading

{
private System.Object lockThis = new System.Object();

public void Function()

{

lock (lockThis)
{
// Access thread-sensitive resources.
}
}

}

The argument provided to the lock keyword must be an object based on a reference type, and is used to define the scope of the lock. In the example above, the lock scope is limited to this function because no references to the object lockThis exist outside the function. If such a reference did exist, lock scope would extend to that object. Strictly speaking, the object provided to lock is used solely to uniquely identify the resource being shared among multiple threads, so it can be an arbitrary class instance. In practice, however, this object usually represents the resource for which thread synchronization is necessary. For example, if a container object is to be used by multiple threads, then the container can be passed to lock, and the synchronized code block following the lock would access the container. As long as other threads lock on the same container before accessing it, then access to the object is safely synchronized.

Generally, it is best to avoid locking on a public type, or on object instances beyond the control of your application. For example, lock(this) can be problematic if the instance can be accessed publicly, because code beyond your control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object. Locking on a public data type, as opposed to an object, can cause problems for the same reason. Locking on literal strings is especially risky because literal strings are interned by the common language runtime (CLR). This means that there is one instance of any given string literal for the entire program, the exact same object represents the literal in all running application domains, on all threads. As a result, a lock placed on a string with the same contents anywhere in the application process locks all instances of that string in the application. As a result, it is best to lock a private or protected member that is not interned. Some classes provide members specifically for locking. The Array type, for example, provides SyncRoot. Many collection types provide a SyncRoot member as well.

For more information on the lock keyword, see:

Monitors

Like the lock keyword, monitors prevent blocks of code from simultaneous execution by multiple threads. The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit. This is just like using the lock keyword. In fact, the lock keyword is implemented with the Monitor class. For example:

lock (x)
{
DoSomething();
}

This is equivalent to:

System.Object obj = (System.Object)x;
System.Threading.Monitor.Enter(obj);
try

{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(obj);
}

Using the lock keyword is generally preferred over using the Monitor class directly, both because lock is more concise, and because lock insures that the underlying monitor is released, even if the protected code throws an exception. This is accomplished with the finally keyword, which executes its associated code block regardless of whether an exception is thrown.

For more information on monitors, see Monitor Synchronization Technology Sample.

Synchronization Events and Wait Handles

Using a lock or monitor is useful for preventing the simultaneous execution of thread-sensitive blocks of code, but these constructs do not allow one thread to communicate an event to another. This requires synchronization events, which are objects that have one of two states, signaled and un-signaled, that can be used to activate and suspend threads. Threads can be suspended by being made to wait on a synchronization event that is unsignaled, and can be activated by changing the event state to signaled. If a thread attempts to wait on an event that is already signaled, then the thread continues to execute without delay.

There are two kinds of synchronization events: AutoResetEvent, and ManualResetEvent. They differ only in that AutoResetEvent changes from signaled to unsignaled automatically any time it activates a thread. Conversely, a ManualResetEvent allows any number of threads to be activated by its signaled state, and will only revert to an unsignaled state when its Reset method is called.

Threads can be made to wait on events by calling one of the wait methods, such as WaitOne, WaitAny, or WaitAll. WaitHandle..::.WaitOne()()() causes the thread to wait until a single event becomes signaled, WaitHandle..::.WaitAny()()() blocks a thread until one or more indicated events become signaled, and WaitHandle..::.WaitAll()()() blocks the thread until all of the indicated events become signaled. An event becomes signaled when its Set method is called.

In the following example, a thread is created and started by the Main function. The new thread waits on an event using the WaitOne method. The thread is suspended until the event becomes signaled by the primary thread that is executing the Main function. Once the event becomes signaled, the auxiliary thread returns. In this case, because the event is only used for one thread activation, either the AutoResetEvent or ManualResetEvent classes could be used.

using System;
using System.Threading;


class ThreadingExample
{
static AutoResetEvent autoEvent;

static void DoWork()

{
Console.WriteLine(" worker thread started, now waiting on event...");
autoEvent.WaitOne();
Console.WriteLine(" worker thread reactivated, now exiting...");

}

static void Main()
{
autoEvent = new AutoResetEvent(false);


Console.WriteLine("main thread starting worker thread...");
Thread t = new Thread(DoWork);

t.Start();

Console.WriteLine("main thread sleeping for 1 second...");
Thread.Sleep(1000);

Console.WriteLine("main thread signaling worker thread...");

autoEvent.Set();
}
}

For more examples of thread synchronization event usage, see:

Mutex Object

A mutex is similar to a monitor; it prevents the simultaneous execution of a block of code by more than one thread at a time. In fact, the name "mutex" is a shortened form of the term "mutually exclusive." Unlike monitors, however, a mutex can be used to synchronize threads across processes. A mutex is represented by the Mutex class.

When used for inter-process synchronization, a mutex is called a named mutex because it is to be used in another application, and therefore it cannot be shared by means of a global or static variable. It must be given a name so that both applications can access the same mutex object.

Although a mutex can be used for intra-process thread synchronization, using Monitor is generally preferred, because monitors were designed specifically for the .NET Framework and therefore make better use of resources. In contrast, the Mutex class is a wrapper to a Win32 construct. While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by the Monitor class. For an example of using a mutex, see Mutexes.

Safe Thread Synchronization

http://msdn.microsoft.com/en-us/magazine/cc188793.aspx



Safe Thread Synchronization
Jeffrey Richter

By far, the most common use of thread synchronization is to ensure mutually exclusive access to a shared resource by multiple threads. In the Win32® API, the CRITICAL_SECTION structure and associated functions offers the fastest and most efficient way to synchronize threads for mutually exclusive access when the threads are all running in a single process. The Microsoft® .NET Framework doesn't expose a CRITICAL_SECTION structure, but it does offer a similar mechanism allowing mutually exclusive access among a set of threads running in the same process. This mechanism is made possible by way of SyncBlocks and the System.Threading.Monitor class.
In this column, I'm going to explain how this common use of thread synchronization is exposed via the .NET Framework. Specifically, I'm going to explain the motivation for why SyncBlocks and Monitors were designed the way they are and how they work. Then, at the end of this column, I'm going to explain why this design is horrible and show you how to use this mechanism in a good, safe fashion.

The Great Idea
The .NET Framework employs an object-oriented programming structure. This means that developers construct objects and then call the type's members in order to manipulate it. Occasionally, these objects are manipulated by multiple threads, and to ensure that the object's state doesn't become corrupted, thread synchronization must be performed. While designing the .NET Framework, the folks at Microsoft decided to create a new mechanism that would make it easy for developers to synchronize an object.
Here's the basic idea: every object in the heap has a data structure associated with it (very similar to a Win32 CRITICAL_SECTION structure) that can be used for thread synchronization. Then, the framework class library provides methods that, when you pass in a reference to an object, use that data structure for thread synchronization purposes.
In Win32, an unmanaged C++ class with this design would look like the one in Figure 1. In essence, the .NET Framework provides every object with its own CRITICAL_SECTION-like field and takes over the responsibility of initializing and deleting it. The only thing the developer has to do is write some code to enter and leave the field as necessary in each method that required thread synchronization.
Figure 1 A CRITICAL_SECTION for Every Object
class SomeType {
private:
// The private CRITICAL_SECTION field
// associated with each object

CRITICAL_SECTION m_csObject;

public:
SomeType() {
// The constructor initializes the
// object's CRITICAL_SECTION field
InitializeCriticalSection(&m_csObject);
}


~SomeType() {
// The destructor deletes the
// object's CRITICAL_SECTION field
DeleteCriticalSection(&m_csObject);
}

void SomeMethod() {
// In the methods, we use the object's

// CRITICAL_SECTION field to synchronize
// access to the object by multiple threads.

EnterCriticalSection(&m_csObject);
// Execute thread-safe code here...
LeaveCriticalSection(&m_csObject);

}

void AnotherMethod() {
// In the methods, we use the object's
// CRITICAL_SECTION field to synchronize
// access to the object by multiple threads.

EnterCriticalSection(&m_csObject);

// Execute thread-safe code here...
LeaveCriticalSection(&m_csObject);
}
};

Implementing the Great Idea
Now, obviously, associating a CRITICAL_SECTION field with every object in the heap is quite wasteful, especially since most objects never require thread-safe access. So, the .NET Framework team designed a more efficient way to offer the functionality just described. Here's how it works.
When the common language runtime (CLR) initializes, it allocates a cache of SyncBlocks. A SyncBlock is a chunk of memory that can be associated with any object as needed. This SyncBlock contains the same fields that you would find in a Win32 CRITICAL_SECTION structure.
Whenever an object is created in the heap, each object gets two additional overhead fields associated with it. The first overhead field, the MethodTablePointer, contains the memory address to the type's method table. Basically, this pointer makes it possible to obtain the type information about any object in the heap. In fact, when you call System.Object's GetType method internally, this method follows the object's MethodTablePointer field to determine what type the object is. The second overhead field, called the SyncBlockIndex, contains a 32-bit signed integer index into the cache of SyncBlocks.
When an object is constructed, the object's SyncBlockIndex is initialized to a negative value to indicate that it doesn't refer to any SyncBlock at all. Then, when a method is called to synchronize access to the object, the CLR finds a free SyncBlock in its cache and sets the object's SyncBlockIndex to refer to the SyncBlock. In other words, SyncBlocks are associated with an object on the fly when the object needs the synchronization fields. When no more threads are synchronizing access to the object, the object's SyncBlockIndex is reset to a negative number, and the SyncBlock is free to be associated with another object in the future.
Figure 2 Thread Synchronization in .NET
For a concrete representation of this idea, take a look at Figure 2. In the CLR Data Structures section of the figure you can see that there is one data structure for every type that the system knows about; you can also see the set of SyncBlock structures. In the managed heap section of the figure you can see that three objects, ObjectA, ObjectB, and ObjectC, were created. Each object's MethodTablePointer field refers to the type's method table. From the method table, you can tell each object's type. So, we can easily see that ObjectA and ObjectB are instances of the SomeType type while ObjectC is an instance of the AnotherType type.
You'll notice that ObjectA's SyncBlockIndex overhead field is set to 0. This indicates that SyncBlock #0 is currently being used by ObjectA. On the other hand, ObjectB's SyncBlockIndex field is set to -1 indicating that ObjectB doesn't have a SyncBlock associated with it for its use. Finally, ObjectC's SyncBlockIndex field is set to 2 indicating that it is using SyncBlock #2. In the example I've presented here, SyncBlock #1 is not in use and may be associated with some object in the future.
So, logically, you see that every object in the heap has a SyncBlock associated with it that can be used for fast, exclusive thread synchronization. Physically, however, the SyncBlock structures are only associated with the object when they are needed and are disassociated from an object when they are no longer needed. This means that the memory usage is efficient. By the way, the SyncBlock cache is able to create more SyncBlocks if necessary so you shouldn't worry about the system running out of them if many objects are being synchronized simultaneously.

Using Monitor to Manipulate a SyncBlock
Now that you understand the SyncBlock infrastructure, let's examine how to lock an object. To lock or unlock an object you use the System.Threading.Monitor class. All of this type's methods are static. Here is the method you call to lock an object:
public static void Enter(object obj);
When you call the Enter method, it first checks to see if the specified object's SyncBlockIndex is negative and if it is, the method finds a free SyncBlock and records its index in the object's SyncBlockIndex. Once a SyncBlock is associated with the object, this method examines the specified object's SyncBlock to see if another thread currently owns the SyncBlock. If it is currently unowned, then the calling thread becomes the owner of the object. If, on the other hand, another thread owns the SyncBlock when Enter is called, then the calling thread is suspended until the currently owning thread gives up ownership of the SyncBlock.
If you want to code more defensively, then instead of calling Enter, you can call one of the following TryEnter methods:
public static Boolean TryEnter(object obj);

public static Boolean TryEnter(object obj,
int millisecondsTimeout);


public static Boolean TryEnter(object obj,
TimeSpan timeout);
The first version simply checks whether the calling thread can gain ownership of the object's SyncBlock and returns true if it is successful. The other two methods allow you to specify a timeout value indicating how long you'll allow the calling thread to sit around idly and wait for ownership. All the methods will return false if ownership cannot be obtained.
Once ownership is obtained, the code can access the object's fields safely. When finished, the thread should release the SyncBlock by calling Exit:
public static void Exit(object obj);
If the calling thread doesn't own the specified object's SyncBlock, then Exit will throw a SynchronizationLockException. Also note that a thread can own a SyncBlock recursively; every successful call to Enter/TryEnter must be matched by a corresponding call to Exit before the SyncBlock is considered unowned.

Synchronizing the Microsoft Way
Now let's look at Figure 3 for some sample code that shows how to use Monitor's Enter and Exit methods to lock and unlock an object. Note that the implementation of the property requires calls to Enter, Exit, and a temporary variable, dt. This is very important in order to prevent returning a corrupt value. This could happen if a thread calls PerformTransaction at the same time another thread has accessed the property.
Figure 3 Using Enter and Exit Methods
class Transaction {

// Private field holding the time of
// the last transaction performed

private DateTime timeOfLastTransaction;

public void PerformTransaction() {
// Lock this object
Monitor.Enter(this);

// Perform the transaction...

// Record time of the most recent transaction

timeOfLastTransaction = DateTime.Now;

// Unlock this object
Monitor.Exit(this);
}

// Public read-only property returning
// the time of the last transaction
public DateTime LastTransaction {

get {
// Lock this object
Monitor.Enter(this);

// Save the time of the last transaction
// in a temporary variable
DateTime dt = timeOfLastTransaction;


// Unlock this object
Monitor.Exit(this);

// Return the value in the temporary variable
return(dt);
}
}
}

Simplifying the Code with the C# Lock Statement
Because this pattern of calling Enter, accessing the protected resource, and then calling Exit is so common, the C# language offers special syntax to simplify the code. The two C# code fragments in Figure 4 are identical in their function, but the second one is simpler. Using the C# lock statement, you can simplify the Transaction class substantially. In particular, take a look at the new, improved LastTransaction property that is shown in Figure 5; the temporary variable is no longer necessary.
Figure 5 Transaction Class
class Transaction {

// Private field holding the time of
// the last transaction performed

private DateTime timeOfLastTransaction;

public void PerformTransaction() {
lock (this) {
// Perform the transaction...

// Record time of the most recent transaction
timeOfLastTransaction = DateTime.Now;

}
}

// Public read-only property returning
// the time of the last transaction
public DateTime LastTransaction {
get {
lock (this) {
// Return the time of the last transaction

return timeOfLastTransaction;
}
}
}
}
Figure 4 Regular and Simple Lock and Unlock
// Regular function
public void SomeMethod() {
// Lock the object
Object oTemp = this;
Monitor.Enter(oTemp);

try {
// Access the object
...
// Unlock the object
}
finally {
Monitor.Exit(oTemp);
}
// Return
}

// Simple function
public void SomeMethod() {

// Lock the object
lock (this) {

// Access the object
...
// Unlock the object
}

// Return
}
In addition to this simplification, the lock statement ensures that Monitor.Exit is called, releasing the SyncBlock even if an exception occurs inside the try block. You should always use exception handling with thread synchronization mechanisms to ensure that locks are released properly. If you use the C# lock statement, the compiler writes the proper code for you automatically. By the way, Visual Basic® .NET has a SyncLock statement that does the same things as the C# lock statement.

Synchronizing Static Members the Microsoft Way
The Transaction class demonstrates how to synchronize access to an object's instance fields. But, what if your type defines a number of static fields and static methods that access these fields? In this case, you don't have an instance of the type in the heap and, therefore, there is no SyncBlock to be used or object reference to pass to Monitor's Enter and Exit methods.
As it turns out, the block of memory that contains a type's type descriptor is an object in the heap. Figure 2 doesn't show it, but the SomeType Type Descriptor and AnotherType Type Descriptor memory blocks are actually objects themselves and, as such, each has a MethodTablePointer field and a SyncBlockIndex field. This means that a SyncBlock can be associated with a type and a reference to the type object can be passed to the Monitor's Enter and Exit methods. In the version of the Transaction class shown in Figure 6, all of the members have been changed to static and the PerformTransaction method and LastTransaction property have been modified to show how Microsoft expects developers to synchronize access to static members.
Figure 6 New Transaction Class
class Transaction {

// Private field holding the time of
// the last transaction performed

private static DateTime timeOfLastTransaction;

public static void PerformTransaction() {
lock (typeof(Transaction)) {
// Perform the transaction...

// Record time of the most recent transaction

timeOfLastTransaction = DateTime.Now;
}
}

// Public read-only property returning
// the time of the last transaction
public static DateTime LastTransaction {
get {

lock (typeof(Transaction)) {
// Return the time of the last transaction
return timeOfLastTransaction;
}
}
}
}
In the code for the method and property, you no longer see the this keyword being used since it can't be referenced in static members. Instead, I'm passing a reference to the type's type descriptor object to the lock statement. This reference is obtained using the C# typeof operator—this operator returns a reference to the specified type's type descriptor. In Visual Basic .NET, the same functionality is exposed via the GetType operator.

Why the Great Idea isn't So Great
As you can see, the idea of having a synchronization data structure logically associated with every object in the heap sounds like a great idea. But, in real life, this is actually a terrible idea. Let me explain why. Remember the unmanaged C++ code shown at the beginning of this column? If you were coding this yourself, would you ever mark the CRITICAL_SECTION field with public access? Of course not—that would be ridiculous! Making this field public allows any code in the application to manipulate the CRITICAL_SECTION structure. It would then become trivially simple for malicious code to deadlock any threads that used instances of this type.
Well, guess what—the SyncBlock is just like a public synchronization data structure associated with every object in the heap! A reference to any object at all can be passed to Monitor's Enter and Exit methods at any time by any piece of code. In fact, a reference to any type descriptor can be passed to Monitor's methods too.
The code in Figure 7 demonstrates how horrible this situation can be. Here, Main constructs an App object and then enters this object's lock. At some point, a garbage collection occurs (in this code, the garbage collection is forced), and when App's Finalize method gets called, it attempts to lock the object. But, the CLR's Finalize thread can't acquire the lock because the application's primary thread owns the lock. This causes the common language runtime's Finalizer thread to stop—no more objects (in the process which can include multiple AppDomains) can get finalized and no more finalizable objects will ever have their memory reclaimed from within the managed heap!
Figure 7 Threads Banging Heads
using System;
using System.Threading;

class App {
static void Main() {
// Construct an instance of the App object
App a = new App();

// This malicious code enters a lock on
// the object but never exits the lock
Monitor.Enter(a);

// For demonstration purposes, let's release the
// root to this object and force a garbage collection
a = null;
GC.Collect();

// For demonstration purposes, wait until all Finalize
// methods have completed their execution - deadlock!
GC.WaitForPendingFinalizers();

// We never get to the line of code below!
Console.WriteLine("Leaving Main");
}

// This is the App type's Finalize method
~App() {
// For demonstration purposes, have the CLR's
// Finalizer thread attempt to lock the object.
// NOTE: Since the Main thread owns the lock,
// the Finalizer thread is deadlocked!
lock (this) {
// Pretend to do something in here...
}
}
}
Fortunately, there is a solution to this problem. However, it means you must ignore the Microsoft design and recommendations. Instead, you must define a private System.Object field as a member of your type, construct the object, and then use the C# lock or Visual Basic .NET SyncLock statement passing in a reference to the private object. Figure 8 shows how to rewrite the Transaction class so that the object used for synchronization is private to the class object. Likewise, Figure 9 shows how to rewrite the Transaction class where all the members are static.
Figure 9 Transaction with Static Members
class Transaction {

// Private, static Object field
// used purely for synchronization
private static Object objLock = new Object();


// Private field holding the time of
// the last transaction performed
private static DateTime timeOfLastTransaction;

public static void PerformTransaction() {
lock (objLock) {
// Perform the transaction...


// Record time of the most recent transaction
timeOfLastTransaction = DateTime.Now;
}
}

// Public read-only property returning
// the time of the last transaction

public static DateTime LastTransaction {
get {
lock (objLock) {
// Return the time of the last transaction
return timeOfLastTransaction;
}
}

}
}
Figure 8 Transaction with Private Object
class Transaction {

// Private Object field used
// purely for synchronization
private Object objLock = new Object();


// Private field holding the time of
// the last transaction performed
private DateTime timeOfLastTransaction;

public void PerformTransaction() {
lock (objLock) {
// Perform the transaction...


// Record time of the most recent transaction
timeOfLastTransaction = DateTime.Now;
}
}

// Public read-only property returning
// the time of the last transaction

public DateTime LastTransaction {
get {
lock (objLock) {
// Return the time of the last transaction
return timeOfLastTransaction;
}
}
}

}
It seems odd to have to construct a System.Object object just for synchronization with the Monitor class. When you get right down to it, I feel that Microsoft designed the Monitor class improperly. It should have been designed so that you construct an instance of the Monitor type for each type that you intend to synchronize. Then, the static methods should have been instance methods that don't require the use of the System.Object parameter. This would have solved all these problems and would have substantially simplified the programming model for developers.
By the way, if you create complex types with many fields, your methods and properties may need to lock only a subset of the object's fields at any time. You can always lock specific fields by passing the specific field object to lock or pass to Monitor.Enter. Of course, I would only consider doing this if the fields are private (which I always recommend). If you have several fields that you want to lock together, you can either use one of the fields as the one you always pass to lock or Enter. Or, you can construct a System.Object object that you use for the sole purpose of locking a field set. The more finely grained your locking, the better performance and scalability your code will achieve.

Unboxed Instances of Value Types
Before I wrap up this column, I'd like to point out a synchronization bug that took me several hours to track down the first time I ran into it. This code snippet demonstrates the problem:
class AnotherType {

// An unboxed Boolean value type
private Boolean flag = false;

public Boolean Flag {

set {
Monitor.Enter(flag); // Boxes flag and locks the object
flag = value; // The actual value is unprotected
Monitor.Exit(flag); // Boxes flag, attempts to unlock
// the object

}
}
}
You might be surprised to learn that in this code, no thread synchronization occurs! The reason is that flag is an unboxed value type, not a reference type. Instances of unboxed value types do not have the two overhead fields, MethodTablePointer and SyncBlockIndex. This means that an unboxed value type instance can't have a SyncBlock associated with it.
Monitor's Enter and Exit methods require a reference to an object on the heap. When C#, Visual Basic .NET, and many other compilers see code that is trying to pass an unboxed value type instance to a method that requires an object reference, they automatically generate code to box the instance. The boxed instance will have a MethodTablePointer and a SyncBlockIndex so the boxed version can be used for thread synchronization. However, a new boxed instance is created each time a method is called and therefore different objects are being locked and unlocked.
For example, in the last code snippet, when the Flag property's set property accessor method is called, it calls Monitor's Enter method. Enter requires a reference type and so flag is boxed and the pointer to the boxed version is passed to Enter. This boxed object's SyncBlock is now owned by the calling thread. If another thread were to access this property now, then flag would be boxed again making a new object with its own SyncBlock. In addition, the calls to Exit also box the passed value type.
As I said, it took me several hours to discover this problem. If you want to synchronize access to an unboxed value type instance, then you must allocate a System.Object object and use it for synchronization. The code in Figure 10 is the corrected code.
Figure 10 Now There's Synchronization
class AnotherType {

// An unboxed Boolean value type
private Boolean flag = false;

// A private Object field used to

// synchronize access to the flag field
private Object flagLock = new Object();

public Boolean Flag {
set {
Monitor.Enter(flagLock);
flag = value;
Monitor.Exit(flagLock);

}
}
}
By the way, if you use the C# lock statement instead of calling Monitor's Enter and Exit methods directly, then the C# compiler will protect you from accidentally trying to lock a value type. When you pass an unboxed value type instance to the lock statement, the C# compiler produces an error. For example, if you try to pass a Boolean (bool in C#) to the lock statement, the following error is produced: error CS0185: 'bool' is not a reference type as required by the lock statement. The Visual Basic .NET compiler also reports the following error if you attempt to use an unboxed value type instance with its SyncLock statement: error BC30582: 'SyncLock' operand cannot be of type 'Boolean' because 'Boolean' is not a reference type.

Send your questions and comments for Jeff to dot-net@microsoft.com.


Jeffrey Richteris a cofounder of Wintellect (http://www.Wintellect.com), a training, debugging, and consulting firm specializing in .NET and Windows Technologies. He is the author of Applied Microsoft .NET Framework Programming (Microsoft Press, 2002) and several programming books on Windows.

Wednesday, February 25, 2009

Difference between Interface and Abstract Class - C#

1. A class can implement any number of interfaces, while can subclass at most one abstract class.

2. An abstract class can have non-abstract methods, while the methods of an interface are effectively abstract.

3. An abstract class can declare and use variables while an interface can not

4. An abstract class can have methods whose access is public, internal, protected, protected internal or private. Interface members implicitly have public access and no access modifiers(including public) are allowed on interface member declarations.

5. An abstract class can define constructors while interface cannot.