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

推荐订阅源

博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
aimingoo的专栏
aimingoo的专栏
腾讯CDC
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
F
Fortinet All Blogs
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园_首页
B
Blog RSS Feed
D
Docker
M
MIT News - Artificial intelligence
爱范儿
爱范儿
I
InfoQ

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
Synchronous vs asynchronous in .NET core - how decide
Hossein Esmati · 2026-06-26 · via DEV Community

Hossein Esmati

Rule of thumb

If your action waits on something external, make it async. If it’s instant CPU, keep it sync; for expensive CPU, offload.

The core idea

  • Async shines for I/O-bound work (DB calls, HTTP calls, queues, files). It frees the request thread while waiting, so the server can serve more requests with the same thread pool.
  • Sync is fine for trivial, short CPU work (formatting, small calculations) where you’re not awaiting anything and the handler returns in a few milliseconds.

When to choose async

  • You call EF Core (SaveChangesAsync, ToListAsync), HttpClient, Azure SDK (ServiceBusClient, BlobClient), file I/O, or any API with Async methods.
  • You expect latency from a dependency (tens–hundreds of ms).
  • You need cancellation and timeouts (propagate HttpContext.RequestAborted).

When sync is acceptable

  • The action is pure CPU and trivial (e.g., quick math, mapping, input validation) and returns immediately.
  • There are no I/O waits and no benefit from freeing the thread.

If it’s CPU-heavy (image processing, big JSON transforms), do not just make it async—offload to a background queue/worker or a separate compute service. Async won’t make CPU faster.

Pitfalls to avoid

  • Don’t block async: never use .Result / .Wait() on Tasks (deadlocks/thread-pool starvation).
  • Async all the way down: if the controller is async, downstream calls should be too.
  • Don’t fake async: returning Task.Run around synchronous I/O just burns threads.
  • Keep concurrency bounded when fanning out to multiple I/O calls.

Mini decision checklist

  1. Any I/O? → Use async (end-to-end).
  2. Pure CPU?
  • Tiny (≤ a few ms) → Sync is fine.
  • Heavy/variable → Offload to background worker; controller returns 202/Location or uses a queue.

ASP.NET Core examples

Async (I/O-bound) — recommended

[ApiController]
[Route("orders")]
public class OrdersController : ControllerBase
{
    private readonly OrdersDbContext _db;
    private readonly HttpClient _http;

    public OrdersController(OrdersDbContext db, IHttpClientFactory f)
    {
        _db = db;
        _http = f.CreateClient("catalog");
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<OrderDto>> Get(string id, CancellationToken ct)
    {
        var order = await _db.Orders.FindAsync([id], ct);
        if (order is null) return NotFound();

        // Call another service
        var resp = await _http.GetAsync($"/inventory/{order.Sku}", ct);
        resp.EnsureSuccessStatusCode();
        var inv = await resp.Content.ReadFromJsonAsync<InventoryDto>(cancellationToken: ct);

        return Ok(new OrderDto(order, inv));
    }
}

Sync (trivial CPU) — acceptable

[HttpGet("ping")]
public ActionResult<string> Ping() => "pong"; // no I/O, returns immediately

CPU-heavy work — offload rather than “asyncifying”

// Controller: accept request, enqueue, return 202
[HttpPost("render")]
public async Task<IActionResult> Render(RenderRequest req, [FromServices] IBackgroundQueue queue)
{
    var jobId = Guid.NewGuid().ToString("N");
    await queue.EnqueueAsync(jobId, req);
    return Accepted($"/render/{jobId}");
}

// Hosted service: single place that uses CPU, bounded concurrency
public class RenderWorker : BackgroundService
{
    private readonly IBackgroundQueue _q;
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var job in _q.DequeueAllAsync(stoppingToken))
        {
            // CPU-bound work here (e.g., image/video), controlled degree of parallelism
        }
    }
}

Tuning & tips

  • Pass CancellationToken from HttpContext.RequestAborted.
  • Use IHttpClientFactory and async Azure SDKs.
  • For streaming, expose IAsyncEnumerable<T> or chunked responses (async).
  • In ASP.NET Core there’s no UI SynchronizationContext, so ConfigureAwait(false) is usually unnecessary.