Skip to main content
 首页 » 编程设计

c#之Function 还是 async 可以细化吗

2024年02月06日12yjmyzz

我有这个功能:

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 不是很大,请使用同步方法。