Multi-Threading Concept in c# (Questions and answers)
Multithreading is the ability of an operating system to
concurrently run programs that have been divided into threads.
Multithreading offers better utilization of processors and
other system resources.
Example:
A program can spell check and save the data to disk while
sending data to be printed.
Advantages and disadvantages of using multithreading
Advantages:
Simultaneous access to multiple applications
Reduced number of required servers
Improved performance and concurrency
Simplified coding of remote procedure calls and
conversations
Disadvantages:
Code writing, debugging, managing concurrency, testing,
porting existing code is difficult in multithreading and multicontexting.
Programmers need to remove static variables and replace any
code that is not thread-safe to introduce threading into a previously non
threaded application.
Benefits of using the Thread Pool.
The benefits of using a Thread Pool are:
Thread creation and destruction overhead is negated,
Better performance and better system stability.It is better to use a thread pool in cases where the number of threads is very large.
Explain how to create and manage threads using Thread
class in the System.Threading namespace in .NET.
using System.Threading;
private void ThreadTask()
{
int x;
int val;
Random r=new
Random();
while(true)
{
x=this.progressBar1.Step*r.Next(-1,2);
val =
this.progressBar1.Value + x;
if (val
> this.progressBar1.Maximum)
val
= this.progressBar1.Maximum;
else if
(val < this.progressBar1.Minimum)
val
= this.progressBar1.Minimum;
this.progressBar1.Value = val;
Thread.Sleep(100);
}
}
You need to write these lines first:
Thread t1 = new
Thread(new ThreadStart(this.ThreadTask));
t1.IsBackground =
true;
t1.Start();
Explain the purpose of Mutex class in .NET.
System uses synchronization mechanism to make sure that a
resource is used by only one thread at a time when more than one thread needs
to access a shared resource at the same time.
Mutex grants exclusive access to the shared resource to a
single thread.
A second thread that needs to acquire a particular mutex is
suspended until the first thread releases the mutex.
Describe the concepts of Monitor class, the interlocked
class and the ReaderWriterLock class.
Access to objects by is controlled by the Monitor class. It
grants a lock for an object to a single thread.
Critical sections can be access restricted by using object
locks.
While a thread owns the lock for an object, no other thread
can acquire that lock.
Interlocked class provides atomic operations for variables
that are shared by multiple threads.
When two threads are executing concurrently on separate
processors error protection is done.
The methods of this class help protect against errors that
can occur when the scheduler switches contexts while a thread is updating a
variable that can be accessed by other threads.
ReaderWriterLock synchronizes access to a resource. It
allows either concurrent read access for multiple threads, or write access for
a single thread.
A ReaderWriterLock provides better throughput than a simple
one lock a time like Monitor.
Explain about Serialization in .NET. Explain binary
serialization and XML serialization
System.Runtime.Serialization namespace provides
Serialization in .NET.
The IFormatter interface in the namespace contains Serialize
and De-serialize methods that save and load data of a stream.
So we need stream as a container for the serialized
object(s) and a formatter that serializes these objects onto the stream to
implement serialization in .net.
Binary serialization is a mechanism that creates exact
binary copy of the object onto the storage media by writing the data to the
output stream such that it can be used to re-construct the object
automatically.
XML serialization results in strongly typed classes with
public properties and fields that are converted to a serial format for storage
or transport. This XML stream conforms to a specific XML Schema definition
language (XSD) document.
Explain why Serialization.
An object is stored in a file, a database or even in the
memory. However, data to be transferred over a network needs to be in a linear
form for which serialization and deserialization are used.
Advantage of serialization is the ability of an object to be
serialized into a persistent or a non-persistent storage media and then
reconstructing the same object later by de-serializing the object.
Remoting and Web Services depend heavily on Serialization
and De-serialization.
Explain the components that comprise the binary
serialization architecture.
To binary serialize an object we need a FileStream object,
Constructor: FileStream(file_name, FileMode.Create);
And
BinaryFormatter
Constructor: binaryFormatter.Serialize(fileStreamObject,
object1);
What is Formatters? Explain the binary formatter and the
SOAP formatter.
A formatter determines the serialization format for objects.
.NET framework provides Binary formatter and SOAP formatter
which inherit from the IFormatter interface
The Binary Formatter
It provides binary encoding for compact serialization for
storage or socket-based network streams.
It is not appropriate for data to be passed through a
firewall.
The SOAP Formatter
It provides formatting that can be used to enable objects to
be serialized using the SOAP protocol.
The class is used for serialization through firewalls or
diverse systems.
What are the main advantages of binary serialization?
An object is stored in a file, a database or even in the
memory. However, data to be transferred over a network needs to be in a linear
form for which serialization and deserialization are used.
Advantage of serialization is the ability of an object to be
serialized into a persistent or a non-persistent storage media and then
reconstructing the same object later by de-serializing the object.
Also Binary Serialization is faster, supports complex
objects too with read only properties and even circular references.
How do you encapsulate the binary serialization?
public static void SerializeBinary( object o, string
file_name)
{
using (FileStream
fs = new FileStream(file_name, FileMode.Create)) {
BinaryFormatter fmt
= new BinaryFormatter ();
fmt.Serialize(fs,
o);
}
}
How do you implement a custom serialization?
CUSTOM SERIALIZATION implementation
public class A: ISerializable
{
private int
a;
protected
A(SerializationInfo si, StreamingContext sc)
{
this.a = serializationInfo.GetInt32("a");
}
public void
ISerializable.GetObjectData(SerializationInfo si, StreamingContext sc)
{
si.AddValue("a", this.a);
}
}
What is the difference between the SoapFormatter and the
XmlSerializer?
SoapFormatter
SOAP formatter will actually take the field values of an
object and store all of that information in the stream passed.
SoapFormatter is better to serialize arbitrary data
XmlSerializer
XML Serialization would just serialize the public properties
of an object.
The XML Serializer is used typically for serializing simple
types across web services
xmlserializer is better, more flexible and faster
How can I optimize the serialization process?
The first call to a Web Service takes long because
XmlSerializer generate an assembly optimized for each type in memory.
To optimize the serialization process pregeneration of
serialization assembly with Visual Studio or sgen.exe is needed.
Implementing serialization separately can also increase the
performance.
Apartments
COM objects in the process as divided into groups called
apartments. A COM object lives in exactly one apartment, in the sense that its
methods can legally be directly called only by a thread that belongs to that
apartment. Any other thread that wants to call the object must go through a
proxy.
There are two types of apartments: single-threaded
apartments, and multithreaded apartments.
1.Single-threaded Apartments—Single-threaded
apartments consist of exactly one thread, so all COM objects that live in a
single-threaded apartment can receive method calls only from the one thread
that belongs to that apartment. All method calls to a COM object in a
single-threaded apartment are synchronized with the windows message queue for
the single-threaded apartment's thread. A process with a single thread of
execution is simply a special case of this model.
2. Multithreaded Apartments—Multithreaded apartments
consist of one or more threads, so all COM objects that live in an
multithreaded apartment can receive method calls directly from any of the
threads that belong to the multithreaded apartment. Threads in a multithreaded
apartment use a model called free-threading. Calls to COM objects in a
multithreaded apartment are synchronized by the objects themselves.
Synchronizing objects
Lock
Locks are useful when only one thread at a time can be
allowed to modify data or some other controlled resource.
Monitors
Monitors are 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.
Mutex
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.
Semaphore is same as Mutex but it ensures not more than a
specified number of threads can access a resource, or section of code.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.