惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
S
Securelist
小众软件
小众软件
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 司徒正美
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
O
OpenAI News
Cloudbric
Cloudbric
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
TaoSecurity Blog
TaoSecurity Blog
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
V2EX
PCI Perspectives
PCI Perspectives
T
Troy Hunt's Blog
Schneier on Security
Schneier on Security
P
Palo Alto Networks Blog
M
MIT News - Artificial intelligence
V2EX - 技术
V2EX - 技术
阮一峰的网络日志
阮一峰的网络日志
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
Google Developers Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Last Watchdog
The Last Watchdog
The Register - Security
The Register - Security
腾讯CDC
N
News and Events Feed by Topic
C
Check Point Blog
爱范儿
爱范儿
T
Tailwind CSS Blog
Webroot Blog
Webroot Blog
P
Proofpoint News Feed
S
Schneier on Security
MyScale Blog
MyScale Blog
N
News | PayPal Newsroom
Recorded Future
Recorded Future
T
Tenable Blog
I
InfoQ
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Microsoft Security Blog
Microsoft Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
Engineering at Meta
Engineering at Meta

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
C# Async/Await and Delegates/Events: The Concepts Behind Every Responsive Application
Manohari Jayachandran · 2026-06-20 · via DEV Community

Every endpoint in the C# API powering my techstackblog uses async/await. Every LINQ query I write is secretly built on delegates. These two concepts are usually taught in separate chapters, but in real production code they constantly overlap - an event handler is often async, and a delegate parameter is often awaited.

This post covers both, with the analogies that made them click for me and the mistakes I see most often in production code.

Part 1 — Async and Await

The Analogy

Imagine ordering food at a restaurant.

A synchronous waiter takes your order, walks to the kitchen, and stands there waiting for your food to finish cooking - completely blocked from serving any other table the entire time.

An asynchronous waiter takes your order, hands it to the kitchen, and immediately goes to serve other tables. When the kitchen finishes, the waiter is notified and brings the food over. One waiter handles many tables efficiently instead of freezing on one slow task.

async/await in C# is that asynchronous waiter. The thread handling your request is not blocked waiting on a slow database call - it gets released to handle other work and resumes once the data is ready.

The Problem It Actually Solves

Without async, a thread that calls a database query sits completely idle for the duration of that call - often 100-300 milliseconds for typical queries. Under load, every concurrent request needs its own thread sitting idle, and you run out of threads fast.

With async, the same thread that started the database call gets returned to the pool immediately after calling await. It goes and handles a different request. When the database responds, the original method resumes often on a different thread entirely. The result is the same hardware handling dramatically more concurrent requests.

Basic Syntax

The async keyword marks a method as asynchronous. The await keyword pauses execution at that point without blocking the thread - it's pausing the method, not the thread. Task represents work that completes at some
point in the future.

A typical async method looks like this: mark the method with async, return Task or Task of some type, and use await wherever you call another async method inside it.

Task vs Task<T> vs async void

Task represents async work with no return value - just a signal of completion. Task<T> represents async work that eventually produces a value of type T. Both of these can be awaited, which is essential.

async void should only be used for actual event handlers - UI button click handlers in WPF or WinForms, for example, which require that exact signature. Outside of event handlers, avoid async void entirely. You cannot await it, which means you cannot know when it completes or catch exceptions it throws. Those exceptions can crash the entire process instead of being caught gracefully.

Running Multiple Async Operations

Sequential awaiting runs operations one after another - if you await three independent calls that each take 100ms, the total wait is 300ms even though none of them depend on each other.

Task.WhenAll runs them concurrently instead. Start all three without awaiting individually, then await Task.WhenAll on all of them together. The total wait becomes roughly the duration of the slowest single operation, not the sum of all three. For any independent async operations, this is a significant and easy performance win.

Common Async Mistakes

The most common mistake is forgetting await entirely - calling an async method without awaiting it returns the Task object itself rather than the data inside it, which is rarely what you want and is an easy typo to miss.

The most dangerous mistake is calling .Result or .Wait() on a Task to force synchronous behavior. This can cause deadlocks in certain contexts, particularly in older ASP.NET applications, and always defeats the entire
purpose of using async in the first place. The fix is simple: await all the way up the call stack rather than blocking partway through.

A subtler mistake is wrapping something in async unnecessarily when there's no actual asynchronous work happening inside - this adds overhead with no benefit.

Part 2 — Delegates and Events

The Analogy

A delegate is like a job posting that describes the exact shape of work needed - "must accept two numbers, must return one number" - without specifying who fills that role. Any method matching that shape can be
plugged in interchangeably.

An event is like a newsletter subscription. The newsletter publisher doesn't know or care who has subscribed. It simply announces "new issue ready" and every subscriber gets notified automatically. The publisher and its subscribers are completely decoupled from each other.

What a Delegate Actually Is

A delegate is a type-safe reference to a method. You define the delegate type once, describing the parameters and return type a matching method must have. Then any method with that exact signature can be
assigned to a variable of that delegate type and invoked through it.

In practice, you almost never declare custom delegate types in modern C#. Three built-in generic delegates cover the overwhelming majority of real-world use:
Func represents a delegate with a return value, Action represents one with no return value, and Predicate always returns a boolean and is typically used for filtering conditions.

Multicast Delegates

A single delegate variable can reference multiple methods at once using the += operator. When invoked, every attached method runs in the order they were added. This is genuinely useful for scenarios like logging the same message to multiple destinations - console, file, and a telemetry service - by combining three separate Action delegates into one.

What an Event Actually Is

An event is essentially a delegate with restricted access. The class that declares the event can raise it, but nothing outside that class can raise it directly - external code can only subscribe or unsubscribe handlers
using += and -=. This protects the publishing class's control over exactly when the notification fires, which is the core difference between a plain delegate field and a proper event.

The standard pattern uses EventHandler or EventHandler<T> as the delegate type, where T is a custom class deriving from EventArgs that carries whatever data subscribers need. Raising the event uses the null-conditional operator before Invoke, which gracefully does nothing if no one has subscribed rather than throwing a null reference exception.

Why Events Instead of Direct Method Calls

Without events, a publishing class needs to know about and directly call every interested party - adding a new subscriber means editing the publisher's code to add another direct call. This tightly couples the publisher to every single consumer of its notifications.

With events, the publisher simply raises the event and has zero knowledge of who is listening or how many subscribers exist. Adding a new subscriber is just one line of subscription code added externally - the publisher class itself never changes. This is loose coupling in its purest practical form.

Events Combined With Async

In real production systems, event handlers are frequently async themselves - an event fires, and the handler needs to do asynchronous work like sending an alert through an external API. This is one of the rare legitimate contexts for async void, since event handler delegate signatures typically can't be changed to return Task.

Where You're Already Using Delegates Without Realizing It

Every LINQ method that takes a lambda is actually accepting a delegate parameter. Where takes a Func<T, bool> - a delegate that takes one item and returns true or false. Select takes a Func<T, TResult> - a delegate that transforms one item into another shape. OrderBy takes a delegate that extracts the sort key. Every single LINQ chain you write is built entirely on the delegate pattern, even though it rarely feels that way while writing it.

ASP.NET Core middleware is built on the same foundation - the next parameter passed into each middleware delegate is itself a delegate pointing to the next piece of middleware in the pipeline.

Key Lessons From Production

  • Always await all the way up the call stack. Never call .Result or .Wait() on a Task anywhere in application code.

  • Use Task.WhenAll whenever you have multiple independent async operations it's an easy, safe performance improvement that's frequently overlooked.

  • Prefer the built-in Func, Action, and Predicate delegate types over declaring custom delegate types. Custom delegates are rarely necessary in modern C#.

  • Use the null-conditional invoke pattern when raising events - it prevents a null reference exception in the common case where no one has subscribed yet.

  • Reserve async void exclusively for actual event handler signatures. Everywhere else, use async Task so exceptions propagate correctly and the work can be awaited.

  • Recognizing that every LINQ lambda is secretly a delegate makes the entire LINQ API click faster - it stops feeling like special syntax and starts feeling like an extension of something you already understand.

Summary

Async/await keeps applications responsive by releasing threads during slow operations instead of blocking them, allowing far more concurrent work on the same hardware.
Delegates provide type-safe references to methods, letting behavior be passed around as data. Events build on delegates to create loosely coupled systems where publishers and subscribers never need direct knowledge
of each other.

Together, these two concepts are the backbone of responsive, maintainable C# applications - showing up everywhere from REST API controllers to UI event handlers to the LINQ queries written dozens of times a
day without a second thought.


Originally published at TechStack Blog:
https://www.techstackblog.com/post.html?slug=csharp-async-delegates-events-deep-dive

More from the same blog, organized by topic:

Azure: https://www.techstackblog.com/category.html?cat=azure
C# / .NET: https://www.techstackblog.com/category.html?cat=csharp
Web fundamentals: https://www.techstackblog.com/category.html?cat=web
Database: https://www.techstackblog.com/category.html?cat=database

Follow for weekly posts on C#, Azure integration, and cloud engineering.