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

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...