.Net Core

 https://www.google.com/search?q=dotnet+core+interview+questions+in+detail+with+explanation&rlz=1CDGOYI_enIN1144IN1144&hl=en-GB&sourceid=chrome-mobile&ie=UTF-8&aep=47&cud=0&source=chrome.crn.rb&udm=50&mstk=AUtExfBuPINfJxf1Ylz9TM1Tats6FhCZ1jxXH3_Krrtdf_n-LaCrypH6spBl5vmh9_XOUb0sJiaiB3EOYTqI7cpuPSz2q6iEbrxlw-5iyLx1QomCan4fGivSI9Vl5UJEmYjX5UQq5n0sVCFKZR2zl4pngF8rNGqDnnTRZEA&csuir=1&mtid=5bphatyAPcyhnesPsZDdmAY


Dependency Injection & Configuration
  • What is Dependency Injection (DI)?
    • It is a built-in technique for achieving Inversion of Control (IoC).
    • It passes dependencies to classes instead of creating them inside.
    • It improves code testability, maintainability, and loose coupling. 
  • Explain the three service lifetimes in .NET Core DI.
    • Transient: A new instance is created every time it is requested.
    • Scoped: One instance is created per HTTP request lifecycle.
    • Singleton: A single instance is created once and shared globally.  


Middleware & Request Pipeline
  • What is Middleware?
    • It is software components assembled into an application pipeline.
    • It handles HTTP requests and responses.
    • Examples include routing, authentication, logging, and static files. 
  • What is the difference between Use and Run extensions in Middleware?
    • Use: Chains multiple middleware components; can call the next component.
    • Run: Terminates the pipeline; never calls a next component.  

 Explain the .NET request processing architecture

For an ASP.NET Core application, the high-level flow is:

Client
   |
   v
Kestrel
   |
   v
Middleware Pipeline
   |
   +--> Exception Handling
   +--> HTTPS Redirection
   +--> Authentication
   +--> Authorization
   |
   v
Routing
   |
   v
Controller / Minimal API
   |
   v
Application / Business Layer
   |
   v
Repository / EF Core / Dapper
   |
   v
Database

Explain async/await in .NET core

The async and await keywords enable non-blocking, asynchronous programming. They prevent your application from freezing or wasting server resources while waiting for long-running operations to finish.
How it Works Under the Hood
  • The Problem (Synchronous): A thread handles a request. It hits a database call and sits idle, blocked until the database responds. No other work can use that thread.
  • The Solution (Asynchronous): A thread handles a request. It hits an await database call. The thread is immediately released back to the system pool to handle other traffic. When the database finishes, a thread (often a different one) resumes your method.

Why should .Result and .Wait() usually be avoided?
The primary reason to avoid .Result and .Wait() is that they convert asynchronous code back into synchronous code, destroying the performance benefits of async/await and introducing critical stability risks.
Here is exactly what goes wrong when you use them:
1. Thread Starvation
When you use await, the executing thread is released back to the thread pool to handle other incoming web requests while waiting for an operation (like a database query) to finish.
When you use .Result or .Wait(), the current thread is forced to sit completely idle and block until the external operation completes. Under heavy user traffic, this quickly consumes all available threads in the pool, causing the entire application to slow down, reject requests, or crash.

Task vs Thread
In .NET Core, a Thread represents an actual OS-level execution path, while a Task is a higher-level abstraction representing a concurrent operation. [1, 2]
You should almost always use Tasks for modern application development.

Core Differences
FeatureThreadTask
Abstraction LevelLow-level OS primitive.High-level API (Task Parallel Library).
Resource CostExpensive (~1 MB of memory overhead).Lightweight (a few bytes for state management).
Creation TimeSlow (requires OS intervention).Fast (managed entirely by the runtime).
System CleanupManual lifecycle management.Handled automatically by the .NET Thread Pool.
Return ValueCannot easily return a value.Easily returns data using Task<T>.
Chaining / CompositionDifficult to string operations together.Easily chained using await or .ContinueWith().

Explain CancellationToken

A CancellationToken is a lightweight mechanism in .NET used to signal that a long-running asynchronous operation should be stopped before it finishes naturally.
It prevents your application from wasting CPU cycles, memory, and database connections on requests that the user or system has already abandoned.

How It Works: The Two-Part System
Cancellation relies on a cooperative pattern divided into two distinct parts:
  1. The Source (CancellationTokenSource): This is the controller. It triggers the cancellation event (e.g., due to a timeout or a user clicking a "Cancel" button).
  2. The Token (CancellationToken): This is the listener. It is passed down into your asynchronous methods so they can monitor whether a cancellation has been requested.

Explain garbage collection

Garbage Collection (GC) is an automatic memory manager that tracks, allocates, and frees up system memory for your application so you do not have to do it manually. [1, 2, 3, 4, 5]

The 3 Core Phases of GC
When the Garbage Collector runs, it stops the application threads (for a brief moment) and goes through three distinct phases: [1, 2, 3]
[ Phase 1: Marking ] ──► Identifies all objects still in use (alive)
        │
[ Phase 2: Relocating ] ─► Updates memory references to new locations
        │
[ Phase 3: Compacting ] ─► Deletes dead objects and squashes remaining memory together
  1. Marking: The GC starts from application "roots" (like static variables or CPU registers) and builds a graph of all connected objects. Any object found is marked as live.
  2. Relocating: The GC updates the reference pointers for the objects that are about to be moved in memory.
  3. Compacting: The GC deletes the unreferenced (dead) objects and moves the live objects closer together to eliminate fragmented, empty spaces.

The Generational System
The heap is divided into three generations to optimize performance. This is based on the rule of thumb that newer objects tend to have shorter lifetimes, while older objects stick around longer.
  • Generation 0 (Gen 0):
    • Contains newly allocated, short-lived objects (e.g., temporary variables).
    • GC happens here most frequently and is incredibly fast.
  • Generation 1 (Gen 1):
    • Acts as a buffer zone between short-lived and long-lived objects.
      • Objects that survive a Gen 0 garbage collection get promoted to Gen 1.
  • Generation 2 (Gen 2):
    • Contains long-lived objects (e.g., static data, application configuration).
    • A Gen 2 collection is also called a Full Garbage Collection because it checks the entire heap. This takes the most time and processing power. [1, 2, 3, 4, 5]
The Exception: Large Object Heap (LOH)
Objects that are 85,000 bytes or larger skip Gen 0 entirely. They go straight into a separate area called the Large Object Heap (LOH). Copying large chunks of memory is slow, so the GC does not automatically compact the LOH. It only deletes dead items and leaves empty gaps, though modern .NET versions allow you to configure manual LOH compaction if needed.


Comments

Popular posts from this blog

TRIGGER in sql server

What is the importance of EDMX file in Entity Framework

Filters in ASP.NET MVC