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...

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 ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...