Skip to main content

C# : Interview questions (46-50)

 

 Questions :

  • Explain the purpose of the lock statement in C#.
  • What is a semaphore?
  • How do you handle asynchronous programming in C#?
  • What is the "async" and "await" keywords used for?
  • Explain the difference between "Task" and "Thread" in C#.

Answers :

Purpose of the lock Statement in C#:

The lock statement in C# is used to synchronize access to shared resources in a multithreaded environment. It ensures that only one thread at a time can execute a critical section of code by acquiring an exclusive lock on a specified object, known as a synchronization object or lock object.

object lockObject = new object();

lock (lockObject)
{
    // Critical section: Access shared resources
}

In this example, the lock statement ensures that only one thread can enter the critical section of code at a time by acquiring a lock on the lockObject. Other threads attempting to enter the same critical section will be blocked until the lock is released.

2. Semaphore:

A semaphore in C# is a synchronization primitive that controls access to a shared resource by maintaining a count of the number of threads allowed to access the resource simultaneously. It allows multiple threads to enter a critical section of code up to a specified limit.

Semaphore semaphore = new Semaphore(3, 3); // Allow up to 3 concurrent threads

semaphore.WaitOne(); // Acquire a semaphore permit
try
{
    // Critical section: Access shared resources
}
finally
{
    semaphore.Release(); // Release the semaphore permit
}

In this example, the semaphore allows up to three concurrent threads to enter the critical section of code by acquiring and releasing semaphore permits using the WaitOne and Release methods, respectively.

3. Handling Asynchronous Programming in C#:

Asynchronous programming in C# allows you to perform non-blocking operations and improve the responsiveness and scalability of applications. It is commonly used for tasks such as I/O-bound operations, network communication, and parallel processing.

4. "async" and "await" Keywords:

The async and await keywords in C# are used to define and await asynchronous operations, respectively. The async modifier is applied to methods to indicate that they contain asynchronous code, while the await operator is used to asynchronously wait for the completion of an asynchronous operation without blocking the calling thread.

async Task<int> GetDataAsync()
{
    // Asynchronous operation
    await Task.Delay(1000);
    return 42;
}

async Task MyMethodAsync()
{
    int result = await GetDataAsync();
    Console.WriteLine("Result: " + result);
}

In this example, the GetDataAsync method contains an asynchronous operation simulated by Task.Delay. The await operator asynchronously waits for the completion of the asynchronous operation, allowing the calling thread to continue executing other tasks in the meantime.

5. Difference between Task and Thread in C#:

  • Thread:
    • Threads represent individual paths of execution within a process.
    • Threads are managed by the operating system and have their own execution context, including stack and register state.
    • Creating and managing threads directly can be resource-intensive and less scalable.
  • Task:
    • Tasks represent asynchronous operations that may or may not run on a separate thread.
    • Tasks are managed by the Task Parallel Library (TPL) and provide a higher-level abstraction for asynchronous programming.
    • Tasks are more lightweight and scalable compared to threads, as they can be executed on thread pool threads or other synchronization contexts.

In summary, tasks provide a higher-level abstraction for asynchronous programming and are preferred over threads for most asynchronous operations in C#.

C# : Interview questions (51-55)

Comments

Popular posts from this blog

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."

C# : 12.0 : Primary constructor

Introduction In C# 12.0, the introduction of the "Primary Constructor" simplifies the constructor declaration process. Before delving into this concept, let's revisit constructors. A constructor is a special method in a class with the same name as the class itself. It's possible to have multiple constructors through a technique called constructor overloading.  By default, if no constructors are explicitly defined, the C# compiler generates a default constructor for each class. Now, in C# 12.0, the term "Primary Constructor" refers to a more streamlined way of declaring constructors. This feature enhances the clarity and conciseness of constructor declarations in C# code. Lets see an simple example code, which will be known to everyone. public class Version { private int _value ; private string _name ; public Version ( int value , string name ) { _name = name ; _value = value ; } public string Ve

C# : Understanding Types of Classes

In C#, classes serve as the building blocks of object-oriented programming, providing a blueprint for creating objects. Understanding the types of classes and their applications is crucial for designing robust and maintainable software. In this blog, we’ll delve into various types of classes in C#, accompanied by real-world scenarios and code snippets for a practical understanding. 1. Regular (Instance) Classes Definition: Regular classes are the most common type and are used to create instances or objects. They can contain fields, properties, methods, and other members. Example Scenario: A Person class representing individual persons with properties like Name and Age. public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } 2. Static Classes Definition: A static class cannot be instantiated and can only contain static members (methods, properties, fields). It’s often used for utility functions. Example Scenario: A MathUtility cla