首页 > 解决方案 > 并行循环中的静态与实例在内存和性能方面更好

问题描述

我想知道解决以下问题的更好方法是什么。我有一种情况,我将进行服务调用和数据库调用,并且根据输入我将进行一些计算并返回这两者之间的一些不匹配。

我有以下示例片段:如果有人可以建议将类设为静态更好还是实例方法更好,因为调用将来自 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;


    }
}

标签: c#.netperformanceoptimization

解决方案


在我看来,准备一个提供一组类实例的缓存并在需要时从缓存中获取实例是有意义的。最好避免在执行并行操作期间创建新的类实例,因为它可能会导致特定的 GC 操作可能会阻塞所有正在运行的线程(大多数它们在单个线程中运行,但如果它们阻塞应用程序,这是一个问题)。顺便说一句:检查正在发生的事情的最佳方法是使用一些配置文件工具。我更喜欢 Microsoft 提供的 PerfView,因为它有助于诊断 GC 问题。


推荐阅读