c# - 执行存储过程列表的性能问题

标签 c# multithreading performance loops

我在启动 Windows 服务时遇到了一些性能问题,第一轮我的 lstSps 很长(大约 130 个存储过程)。有没有办法加快速度(除了加快存储过程)?

当 foreach 结束并进入第二轮时,它会更快,因为在 TimeToRun() 上返回 true 的并不多。但是,我担心的是第一次,因为有更多的存储过程要运行。

我已经考虑过制作一个数组和一个 for 循环,因为我读到它更快,但我相信问题是因为过程需要很长时间。我可以用更好的方式构建它吗?也许使用多个线程(一个用于每次执行)或类似的东西?

非常感谢一些提示:)

编辑:澄清一下,它的方法 HasResult() 正在执行 SP:s 并且看起来需要时间..

lock (lstSpsToSend)
{
    lock (lstSps)
    {
        foreach (var sp in lstSps.Where(sp => sp .TimeToRun()).Where(sp => sp.HasResult()))
        {
            lstSpsToSend.Add(sp);
        }
    }
}

while (lstSpsToSend.Count > 0)
{
    //Take the first watchdog in list and then remove it
    Sp sp;
    lock (lstSpsToSend)
    {
        sp = lstSpsToSend[0];
        lstSpsToSend.RemoveAt(0);
    }

    try
    {
        //Send the results
    }
    catch (Exception e)
    {
        Thread.Sleep(30000);
    }
}

最佳答案

我会做的是这样的:

int openThread = 0;
ConcurrentQueue<Type> queue = new ConcurrentQueue<Type>();
foreach (var sp in lstSps)
{
    Thread worker = new Thread(() =>
        {
            Interlocked.Increment(ref openThread);
            if(sp.TimeToRun() && sp.HasResult)
            {
                queue.add(sp);
            }
            Interlocked.Decrement(ref openThread);
        }) {Priority = ThreadPriority.AboveNormal, IsBackground = false};
        worker.Start();
}
// Wait for all thread to be finnished
while(openThread > 0)
{
    Thread.Sleep(500);
}

// And here move sp from queue to lstSpsToSend

while (lstSpsToSend.Count > 0)
{
    //Take the first watchdog in list and then remove it
    Sp sp;
    lock (lstSpsToSend)
    {
        sp = lstSpsToSend[0];
        lstSpsToSend.RemoveAt(0);
    }

    try
    {
        //Send the results
    }
    catch (Exception e)
    {
        Thread.Sleep(30000);
    }
}

关于c# - 执行存储过程列表的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30981866/

相关文章:

python - 缓存生成器

java - Android Scanner 读到一个分隔符 (UseLimiter)

c# - 统一: What's the difference between a PlayMode UnityTest and an EditMode UnityTest?

java - 线程安全输入验证

java - 抛出异常的哪一部分是昂贵的?

performance - 提高二维图像 'tracing' CUDA 内核性能的技巧?

C# JsonConvert - 具有多种类型的列表列表

c# - WPF 中的全局鼠标 Hook

java - 为什么Thread.isInterrupted()总是返回false?

java - Java 中并发友好链表中的节点特定锁定