c# - 并行循环中的静态与实例在内存和性能方面更好
问题描述
我想知道解决以下问题的更好方法是什么。我有一种情况,我将进行服务调用和数据库调用,并且根据输入我将进行一些计算并返回这两者之间的一些不匹配。
我有以下示例片段:如果有人可以建议将类设为静态更好还是实例方法更好,因为调用将来自 Parallel.for,多个线程将同时使用它。
//Sample Call ..actually will be controllig no of parallel calls using MAxDegreeofparallelism
Parallel.For(1, 10, i =>
{
SomeClass c = new SomeClass();
var res=c.SomeMethod("test", "test");
});
public class SomeClass
{
private readonly IDbRepositroy _IDbRepository =null;
private readonly IServiceRepositroy _IServiceRepositroy = null;
public SomeClass()
{
_IDbRepository = new DbRepository(); // Can do DI
_IServiceRepositroy = new ServiceRepositroy(); // Can DO DI
}
//Here Return Type is shown as string but can a new class object of errors
public List<Errors> SomeMethod(string param1,string param2)
{ var err = new List<Errors>();
var dbData = _IDbRepository.GetDbData(param1, param2);
var serviceData = _IServiceRepositroy.GetServiceData(param1, param2);
//Based on Servcie Data and DB data Calculate erros and return
//Code Logic
//Multiple Logic
return err;
}
}
解决方案
在我看来,准备一个提供一组类实例的缓存并在需要时从缓存中获取实例是有意义的。最好避免在执行并行操作期间创建新的类实例,因为它可能会导致特定的 GC 操作可能会阻塞所有正在运行的线程(大多数它们在单个线程中运行,但如果它们阻塞应用程序,这是一个问题)。顺便说一句:检查正在发生的事情的最佳方法是使用一些配置文件工具。我更喜欢 Microsoft 提供的 PerfView,因为它有助于诊断 GC 问题。
推荐阅读
- rest - 在具有上下文路径的 Spring Boot 应用程序中使用 API 网关时,HATEOAS 路径无效
- css - Angular2禁用CSS捆绑
- docker - 如何识别哪个容器拥有哪个覆盖目录?
- ios - 在登录屏幕上实现了 AWS cognito 身份验证,API 在 UWP 和 android 平台上被击中,但在 IOS 上没有
- java - Java - 无法访问特定的 Windows 注册表文件夹/值
- angular - Angular 6 - Sidenav 与 ngx-translate 重叠内容
- angular5 - 在 Angular 5 中,通过 http 发送数据
- png - zlib 标头如何存储在 png 中的多个 IDAT 块中
- git - 文件在合并期间被替换
- node.js - Node js模块返回未定义