Tech Point Fundamentals

Sunday, August 14, 2022

C# Interview Questions and Answers - Part 13

C# Interview Questions and Answers - Part 13

csharp-interview-questions-and-answers-part1

Are you preparing for the C# Interview? If yes, then you are at the right place. This is the C# Interview Questions and Answers article series. Here we will see the Top 150+ C# Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:



Please read the complete Design Patterns Interview Questions and Answers series here.


Introduction


This is the 13th part of this C# Interview Questions and Answers article series. Each part contains 10 C# Interview Questions with Answers. Please read all the C# Interview Questions list here.

I will highly recommend you to please read the previous parts over here before continuing the current part:





C# Interview Questions and Answers - Part 13


Q131. What is TPL in the .Net? Why TPL is required in C#?

The TPL stands for a Task Parallel Library in C#. Parallelism is the ability to have parallel execution of tasks on a system that has multiple cores. In C# parallel programming is introduced in the .NET Framework 4. 

The .NET Framework 4 introduces Task Parallel Library (TPL) that makes it easier for developers to write parallel programs that target multi-core machines which improves the performance.

The Task Parallel Library is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available.

The TPL is based on the concept of a task, which represents an asynchronous operation. Parallel Programming is a type of programming where many calculations are carried out simultaneously.



But for parallel programming, the problem or task must have the following properties:

  • The tasks must be independent.
  • The order of the execution does not matter.

The TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details. However, not all code is suitable for parallelization.

Types of Parallelism: There can be two types of Parallelism based on the task type that they perform:

1. Data parallelism: In Data Parallelism, the operation is applied to each and every element of a collection. So each process does the same work on unique and independent pieces of data. For data parallelism C# provide Parallel.For and Parallel.ForEach.

2. Task parallelism: In Task Parallelism multiple independent and isolated computations are executed in parallel. So each process performs a different function that is independent. 
For task parallelism C# provide Parallel.Invoke.



Q132. What is the difference between ForEach and Parallel.ForEach loop in C#?

In C# parallel programming is introduced in the .NET Framework 4. Parallelism is the ability to have parallel execution of tasks on a system that has multiple cores.

The Task Parallel Library (TPL) provides two methods i.e. Parallel.For and Parallel.Foreach which are conceptually the “for” and “for each” loops, except that, they use multiple threads to execute multiple iterations at the same time on a machine with multiple cores.

The Parallel ForEach in C# provides a parallel version of the standard, sequential Foreach loop. In a standard Foreach loop, each iteration processes a single item from the collection and will process all the items one by one only. However, the Parallel Foreach method executes multiple iterations at the same time on different processors or processor cores. 

The Parallel.ForEach method splits the work to be done into multiple tasks, one for each item in the collection. Parallel.ForEach is like the foreach loop in C#, except the foreach loop runs on a single thread and processing takes place sequentially, while the Parallel.ForEach loop runs on multiple threads and the processing takes place in a parallel manner.



A Parallel.ForEach loop works like a Parallel.For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment.
The more processors on the system, the faster the parallel method runs. For some source collections, a sequential loop may be faster, depending on the size of the source and the kind of work the loop performs. 

In a Parallel.For or Parallel.ForEach loop, you cannot use the same Break or Exit statement that is used in a sequential loop because those language constructs are valid for loops, and a parallel “loop” is actually a method, not a loop. Instead, you use either the Stop or Break method.

In C# Parallel.ForEach loop runs on multiple threads and processing takes place in a parallel way. The Parallel.ForEach loop is only available in C# 4.0 and above. So before C# 4.0 we cannot use it. To use Parallel.ForEach loop we need to import System.Threading.Tasks namespace in using directive.

To use Parallel.ForEach with a non-generic collection, you can use the Enumerable.Cast extension method to convert the collection to a generic collection:

Parallel.ForEach(nonGenericCollection.Cast<object>(), currentElement => { });

You can also use Parallel LINQ (PLINQ) to parallelize the processing of IEnumerable<T> data sources. PLINQ enables you to use declarative query syntax to express the loop behavior.

Parallel.ForEach(collection, i =>
{
long total = DoSomeIndependentTimeconsumingTask();
Console.WriteLine("{0} - {1}", i, total);
});




Q133. What is the difference between Standard For Loop and Parallel.For Loop in C#?

When the iterations are independent of each other, i.e subsequent iterations do not need the state updates made by previous iterations, then in such cases, we can use Task Parallel Library (TPL) to run each iteration in parallel on all the available cores.

In the case of the standard C# for loop, the loop is going to run using a single thread whereas, in the case of Parallel For loop, the loop is going to execute using multiple threads.

The second difference is that, in the case of the standard C# for loop, the loop is iterated in sequential order whereas, in the case of Parallel For loop, the order of the iteration is not going to be in sequential order.



The Parallel Options class is one of the most useful classes when working with multithreading. This class provides options to limit the number of concurrently executing loop methods. 


Using the Degree of parallelism we can specify the maximum number of threads to be used to execute the program. The MaxDegreeOfParallelism property affects the number of concurrent operations run by Parallel method calls that are passed this ParallelOptions instance. A positive property value limits the number of concurrent operations to the set value. If it is -1, there is no limit on the number of concurrently running operations.

Parallel.For(0, number, count =>
{
Console.WriteLine($"value of count = {count}, thread = {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(10);
});



Q134. What is the difference between task, process, and thread?

Process:

The operating system internally makes use of processes for doing the job. A process is a part (component) of the operating system which is responsible for executing the program or application. 

So, to execute each and every program or application, there will be a process. Windows operating system is a multitasking operating system. So it can run multiple processes or tasks at the same time. A process can have multiple threads and each thread can perform a different task. 



Thread:

A thread is a lightweight process. A thread is a unit of a process that is responsible for executing the application code. By default, every process has at least one thread that is responsible for executing the application code and that thread is called Main Thread. So, every application by default is a single-threaded application. But is also possible that the main thread has other child threads as well.
 
In C# all the threading-related classes are available in the System.Threading namespace. The thread class contains one static property i.e. CurrentThread which is going to return the instance of the currently executing thread. 
 
There is a non-static property called Name using which we can set and get the Name of the currently executing thread. By default, the thread does not have any name. If you want then you can provide any name to the thread by using the Name property of the Thread class.

Task:

A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the .NET Framework 4. The Task object is typically executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.



Q135. What is Multithreading? What is the difference between Multithreading vs MultiTasking or Multithreading vs Concurrency?

Multi-tasking means the ability to do multiple tasks at the same time. So Multitasking refers to allowing the application to perform multiple tasks at the same time. 

Multitasking involves often CPU context switching rapidly between the tasks so that users can collaborate with each program together. Unlike multithreading, in multitasking, the processes share separate memory and resources. The multitasking component involves multiprocessing.

In a single threading application, all the code presented in the program will be executed by a single thread only i.e. the Main thread.  In this case, the main thread is responsible to execute all the methods sequentially.



A process can have multiple threads and each thread can perform a different task. The advantage of multi-thread is that the execution takes place simultaneously on different cores.

Multithreading is used to perform multiple tasks on multiple CPU cores and each task can have multiple threads. Unlike multitasking, multithreading provides the same memory and resources to the processes for execution. A multithreading component does not involve multiprocessing.

In C#, the Thread class contains four constructors. All the Thread class constructor that takes one parameter is either of the type ThreadStart or ParameterizedThreadStart which are nothing but a delegate. 



Q136. What is the difference between Concurrency and Parallelism? Are they same as async programming?

The terms concurrency and parallelism are often used in relation to multithreaded programs. Concurrency and parallelism are two confusing concepts. Although they appear to be the same, concurrency, parallelism, and multithreading are not the same thing.

A Concurrency refers to how a single CPU can make progress on multiple tasks seemingly at the same time, Parallelism, on the other hand, is related to how an application can parallelize the execution of a single task - typically by splitting the task up into subtasks which can be completed in parallel.

Concurrency:

In Concurrency, multiple different threads are doing different things at the same time. So concurrency means doing multiple things at the same time but it does not specifically refer to the use of multiple threads. In concurrency when you execute multiple tasks on the single-core and the core switches context (time slicing) between tasks and serves them.

Concurrent collections in .NET are contained inside the System.Collections.Concurrent namespace and provide lock-free and thread-safe implementations of the collection classes. The ConcurrentDictionary class is contained inside the System.Collections.Concurrent namespace and represents a thread-safe dictionary.



Parallelism:

Parallelism means you execute multiple tasks on multiple cores parallelly. Parallel execution is when a computer has more than one CPU or CPU core and makes progress on more than one task simultaneously.

Parallelism is a subset of concurrency and concurrency enables parallelism. So Concurrency is a broader term and Parallelism is a subset of it. 

Concurrency is about Design while Parallelism is about Hardware. In order to achieve concurrency, we need to compose our application logic independently. So Parallelism broadly means achieving concurrency by distributing work across multiple CPUs. 

Parallel.For, Parallel.ForEach and Parallel.Invoke is available in the TPL for parallel programming in C#.



Concurrency and Parallelism: Both Concurrency and Parallelism can be used together in different combinations:

1. Concurrent but Not Parallel:  An application can be concurrent, but not parallel. This means that it makes progress on more than one task seemingly at the same time (concurrently), but the application makes context switches between making progress on each of the tasks until the tasks are completed.

2. Parallel but Not Concurrent: An application can also be parallel but not concurrent. This means that the application only works on a single task at a time, and this task is broken down into subtasks that can be processed in parallel if multiple cores are available. 

3. Neither Concurrent Nor Parallel: An application can also be neither concurrent nor parallel. This means that it works on only one task at a time, and the task is never broken down into subtasks for parallel execution. 

4. Concurrent and Parallel: Finally, an application can also be both concurrent and parallel at the same time. In simple parallel concurrent execution where an application starts up multiple threads which are then executed on multiple CPUs. It is also possible that the application works on multiple tasks concurrently, and it also breaks each task down into subtasks for parallel execution.
 


Async and Await:

Async programming gets mixed up with the other two i.e Concurrency and Parallelism likely because it has something to do with threads. Async describes how individual threads are used.

If you use the term "concurrency" in multithreading then it's not related to async/await at all. If concurrency means doing multiple things simultaneously then async/await supports concurrency by allowing a single thread to start one process and then do something else instead of waiting for the first process to finish.

C# has a language-level asynchronous programming model, which allows for easily writing asynchronous code. The core of async programming is the Task and Task<T> objects, which model asynchronous operations. They are supported by the async and await keywords. 

The await keyword is where the magic happens. It yields control to the caller of the method that performed await, and it ultimately allows a UI to be responsive or service to be elastic. 



Example:

Consider two tasks, T1 and T2, that have to be executed by an application. 

  • These two tasks are in concurrent execution if one is in an execution state while the other is waiting for its turn. As a result, one of the tasks completes ahead of the other. 
  • On the other hand, the two tasks are in parallel execution if both execute simultaneously. To achieve task parallelism, the program must run on a CPU with multiple cores.

In the synchronous method, if a method Foo() takes 20 seconds to complete then the thread used to call that method will do nothing for 20 seconds except wait. 

But if we execute the same method in an asynchronous method, that thread can do other things for 20 seconds. When the command is finished executing, that thread will pick up where the first thread left off. For that we use await keyword before that method call i.e await Foo().



Q137. What is asynchronous programming? What is the use of async and await keywords in C#? 

Asynchronous programming was devised to accommodate for the lag between when a function is called to when the value of that function is returned. Asynchronous programming helps a user flow smoothly through an application. Without asynchronous programming, apps would spend a long time on loading screens until the process is completed.

On the other hand, Synchronous programming follows a strict set of sequences. When the code runs in a synchronous program, it will follow each step of an algorithm. It does so in order and will wait for the present operation to finish before continuing on to the next.

C# has a language-level asynchronous programming model, which allows for easily writing asynchronous code without having to juggle callbacks or conform to a library that supports asynchrony. It follows what is known as the Task-Based Asynchronous Pattern (TAP).



Features of  Async Programming:

  1. Async code can be used for both I/O-bound and CPU-bound code, but differently for each scenario.
  2. Async code uses Task<T> and Task, which are constructs used to model work being done in the background.
  3. The async keyword turns a method into an async method, which allows you to use the await keyword in its body.
  4. All the async methods need to have an await keyword in their body or they will never yield. However, if await is not used in the body of an async method, the C# compiler generates a warning, but the code compiles and runs as if it were a normal method.
  5. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. But await can only be used inside an async method.
  6. An async void should only be used for event handlers because events do not have return types.

The core of async programming is the Task and Task<T> objects, which model asynchronous operations. They are supported by the async and await keywords. On the C# side of things, the compiler transforms your code into a state machine that keeps track of things like yielding execution when an await is reached and resuming execution when a background job has finished.

The await keyword is where the magic happens. It yields control to the caller of the method that performed await, and it ultimately allows a UI to be responsive or service to be elastic. 



Q138. What is a Task in C#? What is the difference between task and thread?

A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the .NET Framework 4. Tasks in C# are basically used to make your application more responsive. 

The Task object is typically executed asynchronously on a thread pool rather than synchronously on the main thread of the application. A task scheduler is responsible for starting the Task and also responsible for managing it. By default, the Task scheduler uses threads from the thread pool to execute the Task.

The .NET framework provides Threading.Tasks class to let you create tasks and run them asynchronously. A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you a result. A task can be used whenever you want to execute something in parallel. Asynchronous implementation is easy in a task, using’ async’ and ‘await’ keywords.



The Task class represents a single operation that does not return a value and that usually executes asynchronously. Task objects are one of the central components of the task-based asynchronous pattern first introduced in the .NET Framework 4. 

A task that does not return a value is represented by the System.Threading.Tasks.Task class. A task that returns a value is represented by the System.Threading.Tasks.Task<TResult> class, which inherits from Task.

Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled, IsCompleted, and IsFaulted properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform.



A Thread Pool in C# is a collection of threads that can be used to perform a number of tasks in the background. Once a thread completes its task, then again it is sent to the thread pool, so that it can be reused. This reusability of threads avoids an application to create a number of threads which ultimately uses less memory consumption.

The Task Parallel Library (TPL) is based on the concept of a task, which represents an asynchronous operation. In some ways, a task resembles a thread or ThreadPool work item, but at a higher level of abstraction.  In general, the Task class will always represent a single operation and that operation will be executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.

Task taskA = new Task(PrintMessage);
taskA.Start();

Task provide more programmatic control than is possible with a thread or work item. Tasks provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.

Thread thread = new Thread(new ThreadStart(PrintMessage));  
thread.Start(); 



Task vs Thread:

  1. The Thread class is used for creating and manipulating a thread while a Task represents some asynchronous operation and is part of the TPL, a set of APIs for running tasks asynchronously and in parallel.
  2. The task can return a result but there is no direct mechanism to return the result from a thread. We need to use a callback delegate in the thread to get the result from a thread.
  3. Task supports cancellation through the use of cancellation tokens. But Thread doesn't.
  4. A task can have multiple processes happening at the same time. Threads can only have one task running at a time.
  5. We can easily implement Asynchronous programming using ’async’ and ‘await’ keywords. While we need to create, run and manage thread explicitly.
  6. A new Thread() is not dealing with Thread pool thread, whereas Task does use thread pool thread.
  7. A Task is a higher-level concept than Thread. So the task is at a higher level of abstraction.




Q139. What is synchronization and why it is important?

Synchronization in C# is a mechanism that makes sure only one process or thread accesses the critical section of the program. All the other threads have to wait until the critical section is free before they can enter it. 

Synchronization is a technique that allows only one thread to access the resource for a particular time. No other thread can interrupt until the assigned thread finishes its task.

In a multithreading program, threads are allowed to access any resource for the required execution time. Threads share resources and execute asynchronously. Accessing shared resources (data) is a critical task that sometimes may halt the system even causing deadlock sometimes. 



Why Synchronization?

  1. Thread Synchronization deals with Deadlock, Starvation, Priority Inversion, and Busy Waiting.
  2. Synchronization is used for achieving mutual exclusion i.e. only one process or thread accesses the critical section of the program.
  3. Synchronization makes sure that no thread or process has an infinite waiting time.
  4. In Synchronization, all the requests are granted in a specific order using synchronization.
  5. Synchronization can be used for resource allocation as well. It makes sure that only one process or thread can use a resource at a time.
  6. It may cause deadlock if synchronization does not handle properly.

Different Methods to manage Synchronization:

The .NET Framework provides a range of types that you can use to synchronize access to a shared resource or coordinate thread interaction. There are multiple ways to manage synchronization in the .Net which can be divided into 4 categories:

  1. Blocking Methods (Join, Sleep, Task.Wait)
  2. Locking Constructs (Lock, Mutex)
  3. Non-Blocking Synchronization
  4. Signaling



Q140. What is the difference between Join and Lock synchronization?

Using Synchronization, you can synchronize access to resources in multithreaded applications. Both Join and Lock are thread synchronization mechanisms in C#.

Join: 

Join is a blocking method of synchronization. In thread synchronization, join is a blocking mechanism that pauses the calling thread. This is done till the thread whose join method was called has completed its execution.

It is similar to Sleep but it does not pause all threads. It pauses the calling thread until the thread whose join method is called has been completed. 

Thread t1 = new Thread(Func1);    
t1.Start();    
Thread t2 = new Thread(Func2);    
t2.Start();    
t1.Join();    
t2.Join(); 



Lock: 

Locking is also a synchronization mechanism. It limits the access to a resource in multiple threads. An exclusive locking mechanism is used for it. There are two main Locking mechanisms:
  • Lock
  • Mutex

The lock is a synchronization method that is used to lock in the current thread so that no other thread can interrupt the execution of the locked thread. After the thread execution is complete, it is unlocked.

It locks the critical section of code so that only one thread can execute the critical section of code at a time. If another thread tries to enter into a critical section of code then it is prevented and blocked and then it will wait until the object is released from the using thread.

public void Display()  
lock (this)  
for (int i = 1; i <= 5; i++)  
Thread.Sleep(100);  
Console.WriteLine("i = {0}", i);  

Mutex:

Mutex stands for Mutual Exclusion. The Mutex type ensures blocks of code are executed only once at a time. It is basically used in a situation where resources have to be shared by multiple threads simultaneously.  The System.Threading.Mutex class grants exclusive access to a shared resource. 


To Be Continued Part-14...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK  for regular updates.

  

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.