我在启动 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/