gpt4 book ai didi

c# - 使用 Task.FromResult 围绕同步函数创建异步包装器?

转载 作者:太空狗 更新时间:2023-10-30 00:40:30 24 4
gpt4 key购买 nike

我正在浏览 tutorial在 asp.net vnext 系列中。我在 tutorial 中遇到了一些东西这没有多大意义:

using System.Linq;
using Microsoft.AspNet.Mvc;
using TodoList.Models;
using System.Threading.Tasks;

namespace TodoList.ViewComponents
{
public class PriorityListViewComponent : ViewComponent
{
private readonly ApplicationDbContext db;

public PriorityListViewComponent(ApplicationDbContext context)
{
db = context;
}

// Synchronous Invoke removed.

public async Task<IViewComponentResult> InvokeAsync(int maxPriority, bool isDone)
{
string MyView = "Default";

// If asking for all completed tasks, render with the "PVC" view.
if (maxPriority > 3 && isDone == true)
{
MyView = "PVC";
}

var items = await GetItemsAsync(maxPriority, isDone);

return View(MyView, items);
}

private Task<IQueryable<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
{
return Task.FromResult(GetItems(maxPriority, isDone));

}
private IQueryable<TodoItem> GetItems(int maxPriority, bool isDone)
{
var items = db.TodoItems.Where(x => x.IsDone == isDone &&
x.Priority <= maxPriority);

string msg = "Priority <= " + maxPriority.ToString() +
" && isDone == " + isDone.ToString();
ViewBag.PriorityMessage = msg;

return items;
}

}
}

他们正在为同步方法创建一个包装器,并且只是调用 Task.FromResults() 所以它是异步的。首先,它仍然会阻塞,所以有什么意义呢?可能在幕后它只是创建一个 TaskCompletionSource 并将结果包装在 Task 对象中。然后他们 await 结果可能只是产生了我认为不需要的额外开销。他们通过 EF 进行的数据库调用仍然是同步的。我在这里遗漏了什么或者是一个不好的例子吗?

最佳答案

这是一个不好的例子。围绕同步操作创建异步包装器没有任何值(value),此类决定通常应留给库使用者。

I believe the only asynchronous methods that should be exposed are those that have scalability benefits over their synchronous counterparts. Asynchronous methods should not be exposed purely for the purpose of offloading: such benefits can easily be achieved by the consumer of synchronous methods

来自 Should I expose asynchronous wrappers for synchronous methods?

虽然有时它是合适的(比如遵守 Task 返回接口(interface)或抽象方法),但情况似乎并非如此。

关于c# - 使用 Task.FromResult 围绕同步函数创建异步包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27231765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com