Multithreading C# Interview Questions

Facebook
Twitter
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

Multithreading refers to the ability of a program to allow execution of two instructions simultaneously while sharing the same resources. Make sure you master mulithreading C# interview questions before your next interview. 

What is the Difference between Synchronous and Asynchronous Tasks?

In C#, multithreading simply means to execute the code instructions in parallel. It is executed in two ways i.e. Synchronous Task and Asynchronous Task.

Synchronous Task

A synchronous task is executed one at a time i.e. when one task is completed, then the second task will begin to execute its instructions. If you execute synchronous task, you need to wait for its completion before moving to the next task.

Asynchronous Task

An asynchronous task can be executed in parallel with other task. It does not need to wait for the completion of previous task and hence allows more task to be completed at one time.

What is Asynchronous Programming Model in C#?

Multithreading is the most powerful feature in any C# program. It has a built-in support of running the threads simultaneously.  Threads can be considered as a separate code of logic or unit working together in a program independently. All the threads are created inside a Main thread. The Common Language Runtime (CLR) automatically creates the foreground thread at the time of starting an application. An Application can then produces more threads along with the main thread to run sequentially or concurrently. Those threads can execute in the background or foreground depending upon the type of the thread. Most of the operating systems are providing ability to create a single threaded application called as Main or UI Thread.

What is the Difference between Async and Await Keywords?

You can execute the code concurrently with the help of the async and await keywords. Let’s take an example of two methods i.e. MethodA and MethodB, both are not dependent on each other and can be called simultaneously. Methods A takes more time then the Methods B to complete its execution. In synchronous calling, MethodA will complete its execution and then Method B will get the chance to execute the code. Whereas, in asynchronous programming model, you can run together without waiting for each other.


await Task.Run(() =>
{
// Do your code here
}

What are the States in the Lifecycle of a Thread?

A thread can acquire one of the following state during its lifecycle:

  • New: Whenever a Thread is created using a new operator of Thread class, it is in the new state and the thread is not alive. To start a thread, you must call the start() method.
  • Runnable: After calling Thread.Start(), the thread is ready to run after calling the start() method and comes in the runnable state. At this time, the thread needs to be selected by the thread scheduler.
  • Running: When the thread scheduler acquires the thread from the ready or runnable state and the thread comes in the running state.
  • Waiting / Blocked: When a thread is still alive but not running or it is waiting for the other thread to finish its execution, it comes in the waiting or blocked state.
  • Dead / Terminated: When the program calls a run method, it comes in the terminated or dead state

How to Create a Thread?

In C#, multithreading can be achieved by using the System.Threading namespace. It is a fundamental library for providing the ability to run the instructions concurrently. It helps in creating the classes and interface to use the multithreaded methods.

Write a Program to Create a Thread in C#?

The following program will show a basic code of the execution of main thread

using System;
using System.Threading; // namespace to support multithreading application

namespace TestApp {
   public class MainProgram {
      public static void Main(string[] args) {
         Thread objThread = Thread.CurrentThread;
         objThread.Name = "Main Application Thread";
         
         Console.WriteLine("This is my {0}", objThread.Name);
         Console.ReadKey();
      }
   }
}
the output of the above program is:

This is my Main Application Thread

What is Context Switching?

In Context Switching, the current state of the process (or thread) can be preserved for a specified period of time that can be restored later and the execution can be resumed from the same point. You can enable the multiple processes to share the same CPU with the help of context switching.

Why Do We Use Sleep Method?

The Thread.Sleep() is a static method, used to suspend the execution of a thread for a specific period of duration. By default, it takes the duration in milliseconds to pause the execution, and after that, it resumes the thread for the execution.

// Calling sleep method to suspend the execution for 500 milliseconds
Thread.Sleep(500);

How Can You Destroy a Thread?

You can destroy or terminate any thread by using the Thread.Abort() method in a program.

What is a Deadlock in Multithreading?

This is the most unwanted scenario where every thread is waiting for a resource, which is occupied by some other thread, thus resulting in a situation where no thread can be executed. It is a complicated situation that can even stops the execution of a running application.

What is Thread Safety?

Thread Safety is a programming technique that ensures the safe execution of multiple threads at a same time i.e. a thread is safe only when it can run without breaking the flow of an application. In multithreaded environments, Deadlocks can be defined as a state in which two or more threads are waiting for each other to finish its execution i.e. Thread A acquires Resource A and at the same time Thread B wants to acquire Resource A, thus leads to frozen situation.

How Can You Achieve Thread Safety?

You can achieve the safety of a thread by using the Monitor or Lock techniques. Monitor can be called directly from any context. It provides synchronizes access to the shared resources among the multiple threads. It can also be achieved by using the other ways:

  • Synchronization
  • Atomic Wrapper Class
  • Volatile Keywords

What is Monitor?

Monitor is used to provide Thread Safety in a multithreaded program. It has different methods to manage a resource sharing.

  • Enter(): It marks the start of a critical section by acquiring an exclusive lock on the requested object.
  • Exit(): It marks the end of a critical section by Releasing an exclusive lock on the specified object.
  • Pules(): It notifies a thread about the object state thread in the waiting queue.
  • Wait(): It blocks the current thread by releasing the lock on an object.
  • PulesAll(): It notifies all the threads in a waiting queue.
  • TryEnter(): It allows to acquire an exclusive lock on the requested object.

What is Lock?

Lock keyword is used to ensure resource sharing by single thread at a time to avoid deadlocks. In multithreaded application, the management of resources is critical as it can bring a serious deadlock in an application. Therefore, it is necessary to manage the resources simultaneously.

What are the problems with Locking?

  • Locking can block resources until the thread completes its execution
  • It adds complexity in the program and limits the scalability of resources
  • If any page fault occurs and thread is rescheduled, all the threads will have to wait
  • the threads which are set on high priority cannot proceed its execution until the low priority thread releases the resource
  • It is extremely difficult to replicate the situation if there is any bug in the programming code
  • It adds additional overhead for each resource at the time of accessing a resource even if the chances of deadlock is rare

What is time slicing in Threads?

Time slicing is the process of allocating time to the threads. the length of a time depends on the processor and Operating Systems. If a thread is unable to complete its execution within the allotted time, it will enter into the pool of ready tasks. This is managed by a circular queue i.e. scheduler executes the first process, second process and so on.

How Can You Describe Inter-Thread Communication?

Inter-Thread Communication is the communication between two synchronized threads. One thread is paused from its execution and allows another thread to enter in the critical section to be executed in a technique. You can use the wait() and notify() methods to implement the inter-thread communication.

What are the Advantages of Multithreading?

  • It provides simultaneous access to the multiple resources
  • It improves performance and concurrency in an application
  • It provides simplified coding for Remote Procedure Calls
  • It provides better use of cache by utilizing same resources
  • It provides better utilization of CPU

What are the Disadvantages of Multithreading?

  • It adds complexity in an application
  • It is difficult to trace the bugs and reproduce it
  • It cannot be used with static variables
  • It adds overheads switching of context
  • It may produce unexpected results at run time
Facebook
Twitter
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.