ZetCode

ASP.NET 任务

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 Task 类。Task 是在现代 .NET 应用程序中编写异步代码的基础。

ASP.NET 是一个跨平台、高性能的 Web 应用构建框架。Task 能够高效地处理 I/O 密集型操作,而不会阻塞线程。

基本定义

Task 代表 .NET 中的异步操作。它是未来工作的一种承诺,可能会返回值,也可能不会。Task 与 async/await 关键字一起使用。

Task 通过允许操作的非阻塞执行来帮助管理并发。它们对于处理大量请求的可伸缩 Web 应用程序至关重要。

在 ASP.NET 中,控制器操作可以返回 Task来支持异步操作。这通过在 I/O 等待期间释放线程来提高服务器吞吐量。

ASP.NET Task 示例

下面的示例演示了在 ASP.NET 中使用 Task 的异步控制器操作。

Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

var app = builder.Build();

app.MapControllers();
app.Run();

这会设置一个具有控制器和 Entity Framework Core 支持的 ASP.NET 应用程序。DbContext 已配置为支持异步数据库操作。

Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly AppDbContext _context;

    public ProductsController(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IActionResult> GetAllProducts()
    {
        var products = await _context.Products.ToListAsync();
        return Ok(products);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetProductById(int id)
    {
        var product = await _context.Products.FindAsync(id);
        if (product == null) return NotFound();
        return Ok(product);
    }

    [HttpGet("expensive")]
    public async Task<IActionResult> GetExpensiveProducts()
    {
        var products = await _context.Products
            .Where(p => p.Price > 100)
            .ToListAsync();
        return Ok(products);
    }
}

此控制器演示了三个使用 Task 的异步操作。每个方法都使用 Entity Framework Core 的异步方法异步执行数据库操作。

GetAllProducts 方法从数据库返回所有产品。使用 ToListAsync 而不是 ToList 来进行异步操作。

GetProductById 方法展示了单个项目的异步检索。FindAsyncFind 方法用于主键查找的异步版本。

GetExpensiveProducts 方法演示了带过滤的异步查询执行。所有数据库操作都是非阻塞的,从而释放了线程。

来源

Microsoft Task 文档

在本文中,我们探讨了 ASP.NET 8 中的 Task。这个强大的功能为可伸缩 Web 应用程序提供了高效的异步编程。

作者

我的名字是 Jan Bodnar,我是一名充满激情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在教学编程方面有十多年的经验。

列出所有 ASP.NET 教程