.Net Core
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
UseandRunextensions 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 coreTheasyncandawaitkeywords 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
awaitdatabase 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.Resultand.Wait()is that they convert asynchronous code back into synchronous code, destroying the performance benefits ofasync/awaitand introducing critical stability risks.Here is exactly what goes wrong when you use them:1. Thread StarvationWhen you useawait, 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.Resultor.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 ThreadIn .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
Feature Thread Task Abstraction Level Low-level OS primitive. High-level API (Task Parallel Library). Resource Cost Expensive (~1 MB of memory overhead). Lightweight (a few bytes for state management). Creation Time Slow (requires OS intervention). Fast (managed entirely by the runtime). System Cleanup Manual lifecycle management. Handled automatically by the .NET Thread Pool. Return Value Cannot easily return a value. Easily returns data using Task<T>.Chaining / Composition Difficult to string operations together. Easily chained using awaitor.ContinueWith().Explain CancellationTokenA 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 SystemCancellation relies on a cooperative pattern divided into two distinct parts:
- 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).- 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 collectionThe 3 Core Phases of GCWhen 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
- 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.
- Relocating: The GC updates the reference pointers for the objects that are about to be moved in memory.
- Compacting: The GC deletes the unreferenced (dead) objects and moves the live objects closer together to eliminate fragmented, empty spaces.
The Generational SystemThe 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):
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
Post a Comment