YouTube Icon

Interview Questions.

Top 100+ C# Developer Multi Threading Interview Questions And Answers - May 27, 2020

fluid

Top 100+ C# Developer Multi Threading Interview Questions And Answers

Question 1. What Is Thread ?

Answer :A thread is basically a separate collection of instruction designed to acting a " specific mission" within the program.

Question 2. What Is Multithreading In C# ?

Answer :Performing multiple mission at identical time all through the execution of a application,is known as multithreading.

C++ Interview Questions
Question 3. What Is The Namespace Used For Multithreading In C# ?

Answer :using System.Threading;

Question four. What Are The Advantage Of Multithreading In C# ?

Answer :There are two important advantage to use of multithreading in c#. Optimize the usage of computer assets such as reminiscence. Save time

C++ Tutorial
Question five. What Are The Classes Used In System.Threading Namespace ?

Answer :Thread Thread Pool Monitor Mutex

C#. NET Interview Questions
Question 6. What Is The Use Of Thread Class In C#?

Answer :The Thread class is used to perform tasks which include creating and setting the concern of a thread.

Question 7. What Are The Main Properties Of Thread Class?

Answer :Priority Thread State IsAlive Current thread Name and so on.

C#. NET Tutorial C Interview Questions
Question 8. What Are The Methods Used In Thread Class?

Answer :

Join
Resume
sleep
Spin Wait
Suspended
Start
Interrupt
Question nine. What Is The Thread Pool Class In C#?

Answer :

The Thread Pool elegance is used,to carry out project along with processing of asynchronous i/o and ready on behalf of every other thread.

MVC Framework Interview Questions
Question 10. What Are The Method Used In Thread Pool Class ?

Answer :

Gettype
Equals
SetMaxThreads
QueueUserWorkItem
C Tutorial
Question 11. What Is Monitor Class In C# ?

Answer :

The Monitor class is used to get right of entry to an object by using granting a lock for the object to a unmarried thread.

LINQ Interview Questions
Question 12. What Are The Methods Used In Monitor Class?

Answer :

Enter
Exit
TryEnter
Wait
GetType
C++ Interview Questions
Question thirteen. What Is Mutex Class In C#?

Answer :

A Mutex is used ,to perform interprocess synchronization and a thread to have exclusive access to shared resources.

MVC Framework Tutorial
Question 14. What Are The Methods Used In Mutex Class ?

Answer :

Equals
close
OpenExisting
SetAccessControl
Release Mutex
Question 15. What Are The Syntax For Creating And Starting A Thread In C#?

Answer :

First outline a delegate:-

Public delegate void start_thread();

Create a brand new thread:-

Thread thread_name = new Thread(new start_thread(method_name));

Windows Presentation Foundation(WPF) Interview Questions
Question 16. How Can We Scheduled A Thread In C# ?

Answer :

We can scheduled the  thread with the help of priority assets of the Thread class.

LINQ Tutorial
Question 17. What Are The Priority Value Used For Scheduling A Thread In C# ?

Answer :

Highest
Normal
AboveNormal
BelowNormal
Lowest
Windows Communication Foundation (WCF) Interview Questions
Question 18. What Are The Two Types Of Thread In C# ?

Answer :

Foreground thread
Background thread
C#. NET Interview Questions
Question 19. What Is The Difference Between Join And Sleep ?

Answer :

You can watch for every other thread to give up by using calling its Join method. For example:

static void Main()

Thread t = new Thread (Go);

t.Start();

t.Join();

Console.WriteLine ("Thread t has ended!");

static void Go()

for (int i = 0; i < 1000; i++) Console.Write ("y");

This prints “y” 1,000 times, followed by “Thread t has ended!” immediately afterward. You can include a timeout when calling Join, either in milliseconds or as a TimeSpan. It then returns true if the thread ended or false if it timed out.

Windows Presentation Foundation(WPF) Tutorial
Question 20. What Is The Difference Between Threads Vs Processes ?

Answer :

A thread is analogous to the operating system process in which your application runs. Just as processes run in parallel on a computer,threads run in parallel within a single process. Processes are fully isolated from each other; threads have just a limited degree of isolation. In particular, threads share (heap) memory with other threads running in the same application. This, in part, is why threading is useful: one thread can fetch data in the background, for instance, while another thread can display the data as it arrives.

Advanced C# Interview Questions
Question 21. What Is The Naming Threads ?

Answer :

Each thread has a Name property that you can set for the benefit of debugging.This is particularly useful in Visual Studio, since the thread’s name is displayed in the Threads Window and Debug Location toolbar. You can set a thread’s name just once; attempts to change it later will throw an exception. The static Thread.CurrentThread property gives you the currently executing thread. In the following example, we set the main thread’s name:

class ThreadNaming

static void Main()

Thread.CurrentThread.Name = "main";

Thread worker = new Thread (Go);

worker.Name = "worker";

worker.Start();

Go();

static void Go()

Console.WriteLine ("Hello from " + Thread.CurrentThread.Name);

Question 22. What Is The Difference Between Monitor.Enter And Monitor.Exit?

Answer :

C#’s lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with a try/finally block. Here’s (a simplified version of) what’s actually happening within the Go method of the preceding   

example:

Monitor.Enter (_locker);

try

if (_val2 != 0) Console.WriteLine (_val1 / _val2);

_val2 = 0;

finally  Monitor.Exit (_locker); 

Calling Monitor.Exit without first calling Monitor.Enter on the same object throws an exception.

Windows Communication Foundation (WCF) Tutorial
Question 23. What Is The Meaning Of Deadlocks?

Answer :

A deadlock happens when two threads each wait for a resource held by the other, so neither can proceed. The easiest  way to illustrate this is with two locks:

object locker1 = new object();

object locker2 = new object();

new Thread (() => 

lock (locker1)

Thread.Sleep (1000);

lock (locker2); // Deadlock

).Start();

lock (locker2)

Thread.Sleep (1000);

lock (locker1); // Deadlock

More problematic deadlocking chains can be created with 3 or more threads.

Deadlocking is one of the hardest issues in multithreading—especially whilst there are numerous interrelated objects. Fundamentally, the difficult problem is that you cannot make certain what locks your caller has taken out.

So, you might innocently lock personal area a inside your elegance x, unaware that your caller (or caller's caller) has already locked discipline b inside elegance y. Meanwhile, another thread is doing the opposite—growing a impasse. Ironically, the problem is exacerbated by way of (proper) object-orientated design styles, because such patterns create name chains that aren't decided till runtime. The popular advice, “lock gadgets in a consistent order to keep away from deadlocks,” although helpful in our preliminary example, is hard to use to the situation just described. A higher approach is to be wary of locking around calling methods in items

which could have references again to your personal object. Also, keep in mind whether you really want to fasten around calling techniques in different lessons (often you do—as we’ll see later—however from time to time there are other alternatives). Relying greater on declarative and data parallelism, immutable kinds, and nonblocking synchronization constructs, can lessen the need for locking.

Asp Dot Net Mvc 4 Interview Questions
Question 24. What Is The Meaning Of Mutex?

Answer :

A Mutex is sort of a C# lock, but it could paintings throughout multiple approaches. In other phrases, Mutex may be pc-huge as

well as utility-extensive. 

With a Mutex class, you name the WaitOne technique to fasten and ReleaseMutex to unencumber. Closing or disposing a Mutex mechanically releases it. Just as with the lock announcement, a Mutex may be launched most effective from the same thread that received it. A not unusual use for a go-manner Mutex is to ensure that best one instance of a software can run at a time. Here’s the way it’s finished:

elegance OneAtATimePlease

static void Main()

// Naming a Mutex makes it to be had laptop-extensive. Use a name it truly is

// specific for your organization and alertness (e.G., include your URL).

The use of (var mutex = new Mutex (false, "oreilly.Com OneAtATimeDemo"))

// Wait some seconds if contended, in case another example

// of this system is still inside the process of shutting down.

If (!Mutex.WaitOne (TimeSpan.FromSeconds (three), fake))

Console.WriteLine ("Another example of the app is strolling. Bye!");

return;

RunProgram();

static void RunProgram()

Console.WriteLine ("Running. Press Enter to exit");

Console.ReadLine();

 

C Interview Questions
Question 25. What Is The Meaning Semaphore ?

Answer :

A semaphore is like a nightclub: it has a sure capability, enforced through a bouncer. Once it’s full, no more people can enter, and a queue builds up outside. Then, for each person that leaves, one individual enters from the top of the queue. The constructor requires no less than  arguments: the wide variety of locations currently to be had within the nightclub and the club’s overall ability.

A semaphore with a capability of one is similar to a Mutex or lock, besides that the semaphore has no “owner”—it’s thread-agnostic. Any thread can name Release on a Semaphore, whereas with Mutex and lock, simplest the thread that acquired the lock can release it. 

Semaphores can be beneficial in proscribing concurrency—stopping too many threads from executing a particular piece of code immediately. In the subsequent example, 5 threads try and enter a nightclub that lets in only three threads in immediately:

magnificence TheClub // No door lists!

Static SemaphoreSlim _sem = new SemaphoreSlim (3); // Capacity of three

static void Main()

for (int i = 1; i <= 5; i++) new Thread (Enter).Start (i);

static void Enter (item identification)

Console.WriteLine (identity + " wants to input");

_sem.Wait();

Console.WriteLine (identity + " is in!"); // Only 3 threads

Thread.Sleep (one thousand * (int) identification); // can be right here at

Console.WriteLine (identity + " is leaving"); // a time.

_sem.Release();

Out Put:

1 desires to enter

1 is in!

2 desires to enter

2 is in!

3 wants to enter

three is in!

Four wants to enter

five wants to input

1 is leaving

four is in!

2 is leaving

five is in!

If the Sleep assertion was instead appearing in depth disk I/O, the Semaphore might enhance basic overall performance

through proscribing excessive concurrent tough-pressure activity.

A Semaphore, if named, can span approaches inside the same way as a Mutex.

Question 26. What Is Synchronization In Respect To Multi-threading In C#?

Answer :

With admire to multi-threading, synchronization is the functionality to control the get right of entry to of a couple of threads to shared resources. Without synchronization, it's miles viable for one Java thread to alter a shared variable while some other thread is inside the method of using or updating equal shared variable. This normally leads to misguided behavior or program.

Asp Dot Net Mvc Interview Questions
Question 27. Explain Different Way Of Using Thread?

Answer :

A Java thread might be implemented via the use of Runnable interface or by using extending the Thread elegance. The Runnable is greater superb, when you are going for multiple inheritance.

MVC Framework Interview Questions
Question 28. What Is The Difference Between Thread.Begin() & Thread.Run() Method?

Answer :

Thread.Begin() method (local technique) of Thread class virtually does the job of running the Thread.Run() method in a thread. If we without delay call Thread.Run() technique it will done in same thread, so does not clear up the cause of making a brand new thread.

Question 29. Why Do We Need Run() & Start() Method Both. Can We Achieve It With Only Run Method?

Answer :

We want run() & begin() method each due to the fact JVM desires to create a separate thread which can't be differentiated from a everyday approach call. So this activity is done by means of begin technique native implementation which has to be explicitly referred to as. Another benefit of having these two methods is we will have any item run as a thread if it implements Runnable interface. This is to keep away from Java multiple inheritance problems with a purpose to make it tough to inherit any other magnificence with Thread. 

Question 30. What Is Threadlocal Class? How Can It Be Used?

Answer :

Below are some key factors approximately ThreadLocal variables 

A thread-neighborhood variable efficaciously gives a separate replica of its fee for every thread that makes use of it.
ThreadLocal times are typically personal static fields in instructions that desire to accomplice country with a thread
In case when more than one threads access a ThreadLocal example, separate reproduction of Threadlocal variable is maintained for each thread.
Common use is visible in DAO sample in which the DAO elegance may be singleton however the Database connection may be maintained separately for every thread. (Per Thread Singleton)
ThreadLocal variable are difficult to recognize and I actually have determined below reference links very useful in getting better information on them 
Question 31. When Invalidmonitorstateexception Is Thrown? Why?

Answer :

This exception is thrown whilst you attempt to name wait()/notify()/notifyAll() any of those methods for an Object from a point to your software in which u are NOT having a lock on that item.(i.E. U r now not executing any synchronized block/method of that item and still attempting to name wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. Since This exception is a subclass of RuntimeException so we r no longer certain to capture it (although u may also if u want to). And being a RuntimeException this exception isn't noted inside the signature of wait(), notify(), notifyAll() methods. 

Question 32. What Is The Difference Between Sleep(), Suspend() And Wait() ?

Answer :

Thread.Sleep() takes the contemporary thread to a "Not Runnable" kingdom for detailed amount of time. The thread holds the video display units it has acquired. For instance, if a thread is running a synchronized block or method and sleep approach is called then no other thread can be able to input this block or method. The sleeping thread can wake up whilst a few other thread calls t.Interrupt on it. Note that sleep is a static technique, meaning it usually affects the modern thread (the one executing sleep technique). A common mistake is attempting to name t2.Sleep() in which t2 is a distinct thread; even then, it's miles the modern-day thread with the intention to sleep, no longer the t2 thread. Thread.Droop() is deprecated method. Its possible to send different threads into suspended state by using creating a suspend approach call. In suspended state a thread keeps all its video display units and cannot be interrupted. This can also purpose deadlocks therefore it's been deprecated. Item.Wait() name also takes the modern thread into a "Not Runnable" kingdom, much like sleep(), however with a mild change. Wait method is invoked on a lock object, now not thread. 

Here is the collection of operations you could assume 

A thread T1 is already jogging a synchronized block with a lock on object - lets say "lockObject"
Another thread T2 involves execute the synchronized block and locate that its already obtained.
Now T2 calls lockObject.Wait() technique for waiting on lock to be release by means of T1 thread.
T1 thread finishes all its synchronized block work.
T1 thread calls lockObject.NotifyAll() to notify all waiting threads that its executed using the lock.
Since T2 thread is first inside the queue of waiting it acquires the lock and starts processing.
Question 33. What Is A Deadlock?

Answer :

Deadlock is a scenario where two or extra threads are blocked forever, looking forward to each different. This may additionally occur while  threads, every having a lock on one aid, try to acquire a lock on the opposite's aid. Each thread would wait indefinitely for the opposite to release the lock, unless one of the person approaches is terminated. In terms of Java API, thread impasse can arise in following conditions: 

When two threads call Thread.Join() on each different.

When two threads use nested synchronized blocks to lock  items and the blocks lock the identical items in different order.

LINQ Interview Questions
Question 34. What Is Starvation? And What Is A Livelock?

Answer :

Starvation and livelock are a lot less common a trouble than impasse, but are nevertheless problems that each dressmaker of concurrent software program is possibly to come upon. 

LiveLock:

Livelock occurs whilst all threads are blocked, or are in any other case unable to proceed because of unavailability of required resources, and the non-existence of any unblocked thread to make the ones sources to be had. In terms of Java API, thread livelock can occur in following conditions: 

When all of the threads in a program execute Object.Wait(zero) on an item with 0 parameter. The software is stay-locked and can not proceed till one or more threads name Object.Notify() or Object.NotifyAll() on the applicable items. Because all of the threads are blocked, neither call may be made.

When all of the threads in a program are caught in endless loops.

Starvation:

Starvation describes a state of affairs in which a thread is unable to gain ordinary get right of entry to to shared resources and is unable to make progress. This occurs whilst shared assets are made unavailable for long intervals with the aid of "greedy" threads. For instance, think an item gives a synchronized method that regularly takes a long term to go back. If one thread invokes this method frequently, different threads that also need frequent synchronized get entry to to the identical object will often be blocked. Starvation happens whilst one thread can't get right of entry to the CPU due to the fact one or greater different threads are monopolizing the CPU. In Java, thread hunger may be as a result of setting thread priorities inappropriately. A lower-priority thread may be starved through higher-priority threads if the better-precedence threads do not yield manage of the CPU sometimes. 

Question 35. How To Find A Deadlock Has Occurred In Java? How To Detect A Deadlock In Java?

Answer :

Earlier versions of Java had no mechanism to handle/stumble on deadlock. Since JDK 1.Five there are some powerful techniques added inside the java.Lang.Management package to diagnose and hit upon deadlocks. The java.Lang.Control.ThreadMXBean interface is management interface for the thread machine of the Java virtual gadget. It has  strategies that could leveraged to locate impasse in a Java utility. 

FindMonitorDeadlockedThreads() - This technique can be used to locate cycles of threads which might be in deadlock waiting to accumulate object monitors. It returns an array of thread IDs which can be deadlocked ready on screen.

FindDeadlockedThreads() - It returns an array of thread IDs which might be deadlocked waiting on monitor or ownable synchronizers.

Question 36. What Is Immutable Object? How Does It Help In Writing Concurrent Application?

Answer :

An item is considered immutable if its nation cannot change after it's far built. Maximum reliance on immutable gadgets is widely ordinary as a legitimate method for developing easy, reliable code. Immutable items are in particular useful in concurrent packages. Since they can't change kingdom, they can not be corrupted via thread interference or located in an inconsistent nation. Examples of immutable gadgets from the JDK encompass String and Integer. Immutable objects significantly simplify your multi threaded program, since they may be 

Simple to construct, test, and use.
Automatically thread-safe and haven't any synchronization problems.
To create a item immutable You want to make the class very last and all its member very last so that when objects gets crated no one can adjust its country. You can gain same functionality by way of making member as non very last but personal and no longer enhancing them except in constructor. 
Windows Presentation Foundation(WPF) Interview Questions
Question 37. How Will You Take Thread Dump In Java? How Will You Analyze Thread Dump?

Answer :

A Thread Dump is a entire list of lively threads. A java thread sell off is a way of locating out what each thread in the JVM is doing at a specific point of time. This is specifically beneficial whilst your java application seems to have some overall performance issues. Thread sell off will assist you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is especially endorsed to take greater than 1 thread dump and examine the consequences based totally on it. Follow below steps to take thread unload of a java procedure 

Step 1 

On UNIX, Linux and Mac OSX Environment run below command: 

ps grep java 

On Windows: 

Press Ctrl+Shift+Esc to open the undertaking supervisor and find the PID of the java technique 

Step 2: 

Use jstack command to print the Java stack traces for a given Java technique PID 

jstack [PID] 

Question 38. What Is A Thread Leak? What Does It Mean In C#?

Answer :

Thread leak is when a utility does not launch references to a thread item nicely. Due to this some Threads do now not get rubbish collected and the range of unused threads grow with time. Thread leak can frequently cause critical issues on a Java application because over a period of time too many threads could be created but not launched and might motive packages to reply sluggish or grasp.

Question 39. How Can I Trace Whether The Application Has A Thread Leak?

Answer :

If an application has thread leak then with time it'll have too many unused threads. Try to discover what type of threads is leaking out.

This can be finished the usage of following methods 

Give particular and descriptive names to the threads created in software. - Add log access in all thread at various entry and go out factors in threads.
Change debugging config stages (debug, data, errors and many others) and analyze log messages.
When you find the elegance that is leaking out threads take a look at how new threads are instantiated and the way they may be closed.
Make positive the thread is Guaranteed to shut properly via doing following - Handling all Exceptions well.
Make sure the thread is Guaranteed to shut nicely by using doing following
Handling all Exceptions well.
Freeing all resources (e.G. Connections, files and so forth) before it closes.
Question 40. What Is Thread Pool? Why Should We Use Thread Pools?

Answer :

A thread pool is a collection of threads on which venture can be scheduled. Instead of making a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the mission. When the thread is completed with the challenge, it adds itself returned to the pool and waits for some other project. One commonplace sort of thread pool is the constant thread pool. This type of pool continually has a exact quantity of threads walking; if a thread is come what may terminated even as it is nonetheless in use, it's far routinely replaced with a new thread. Below are key motives to use a Thread Pool 

Using thread swimming pools minimizes the JVM overhead due to thread introduction. Thread gadgets use a tremendous amount of reminiscence, and in a huge-scale application, allocating and de-allocating many thread items creates a sizable reminiscence control overhead.

You have manipulate over the most variety of duties which are being processed in parallel (= quantity of threads in the pool).

Most of the executor implementations in java.Util.Concurrent use thread pools, which encompass employee threads. This kind of thread exists one after the other from the Runnable and Callable tasks it executes and is regularly used to execute multiple obligations. 

Windows Communication Foundation (WCF) Interview Questions
Question forty one. Can We Synchronize The Run Method? If Yes Then What Will Be The Behavior?

Answer :

Yes, the run approach of a runnable class may be synchronized. If you make run technique synchronized then the lock on runnable object can be occupied before executing the run approach. In case we begin a couple of threads the use of the equal runnable item within the constructor of the Thread then it would paintings. But until the 1st thread ends the 2d thread can not start and till the second thread ends the subsequent cannot begin as all of the threads rely on lock on same object




CFG