c# - Function 还是 async 可以细化吗?

标签 c# .net asp.net-mvc asynchronous async-await

我有这个功能:

public async Task<string> EagerLoadAllAsync<T>(params Expression<Func<T, object>>[] includeProperties) where T : class
{
    var entities = await _repository.EagerLoadAllAsync(includeProperties);
    entities.ForEach(l =>
    {
        var lead = l as Lead;
        if (lead.User != null) 
        {
            // We must reduce the amount of data being sent to the client side
            lead.User = new Domain.Identities.ApplicationUser { FirstName = lead.User.FirstName, LastName = lead.User.LastName, UserName = lead.User.UserName };
        }
    });

    var json = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(entities, Formatting.Indented, new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    }));

    return json;
}

我认为它仍然是 async 它必须运行 awaitable 函数,一个从数据库中获取数据,另一个将其转换为 json.

我想知道中间的 ForEach 循环是否从头开始破坏了 async 方法?

有没有办法让它更async? 它应该更 async 吗?

在我需要减少发送到客户端的数据之前,我有这个功能:

public async Task<string> EagerLoadAllAsync<T>(params Expression<Func<T, object>>[] includeProperties) where T : class
{   
    var json = await Task.Factory.StartNew(async() => JsonConvert.SerializeObject(await await _repository.EagerLoadAllAsync(includeProperties), Formatting.Indented, new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    }));

    return json.Result;
}

最佳答案

Stephan cleary 有一篇关于 the dangers of using Task.Run in ASP.NET 的精彩博文:

The reason is that the ASP.NET runtime has no idea that you’ve queued this work (using Task.Run), so it’s not aware that the background work even exists. For a variety of reasons, IIS/ASP.NET has to occasionally recycle your application. If you have background work running when this recycling takes place, that work will mysteriously disappear.

当我围绕一些异步操作(数据库查询、网络请求等)创建一个 async 方法时,我坚持这样的规则:“一个异步方法应该命中它的 await statement as soon as possible”,这是因为 await 之前的任何代码都将同步运行。您可以选择使用 ConfigureAwait(false) 来避免返回到您的请求上下文,但这通常会很快发生。参见 Best practice to call ConfigureAwait for all server-side code有关更多信息。

关于 ForEach,我肯定会对该部分进行基准测试,以了解它对异步调用的影响有多大。除此之外,请阅读 eric lipperts 关于 ForEach vs foreach 的帖子看看为什么你不应该使用它。

为了 JSON 反序列化,我肯定会继续旋转一个新的 ThreadPool 线程。调用该线程然后同步运行它会花费更多。如果您的 JSON 不是很大,请使用同步方法。

关于c# - Function 还是 async 可以细化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24228873/

相关文章:

asp.net-mvc - 将变量从 [HttpPost] 方法传递到 [HttpGet] 方法

c# - 防止EF Code First继承TPT中的索引

c#使用String格式将字符串读入对象

c# - .NETBeans + 请求范围 - 这可能吗?

c# - Rhino Mocks——断言不与模拟/ stub 交互

c# - Web API 自托管客户端配置

c# - 每次运行后 20 分钟运行线程

c# - 如果元素不存在,如何更新/插入 MongoDB C# 驱动程序中文档的子数组

jquery - parsererror 语法错误 : Unexpected token < - Load Partial View using jQuery Ajax in ASP. NET MVC 4

c# - ASP Net MVC - 在 POST 上发送不同的模型