【发布时间】:2010-11-12 04:18:07
【问题描述】:
并不是说我不欣赏多线程或ThreadPool 的强大功能,但我很害怕我弄坏了一些东西,因为我的速度提高了大约 20 倍(从一分钟多一点下降了 2-3 秒) ThreadPool 的用法比较幼稚。所以我在这里提交我的代码,让比我聪明得多的人撕毁。
我在这里做错了什么,还是这只是一个比我希望的多线程更好的候选者? (是的,这个函数是一个完整的线程:就像我说的,这过去需要一分钟才能运行)
编辑:回答我自己的问题,不,这是坏的:它似乎运行了多次,但在同一个触发器上。这是因为 lambda 的处理方式吗?
private static void CompileEverything()
{
try
{
// maintain the state of our systray icon
object iconLock = new object();
bool iconIsOut = true;
// keep a count of how many threads are still running
object runCountLock = new object();
int threadRunning = 0;
foreach (World w in Worlds)
{
foreach (Trigger t in w.Triggers)
{
lock (runCountLock)
{
threadRunning++;
}
ThreadPool.QueueUserWorkItem(o =>
{
// [snip]: Do some work involving compiling code already in memory with CSharpCodeProvider
// provide some pretty feedback
lock (iconLock)
{
if (iconIsOut)
notifyIcon.Icon = Properties.Resources.Icon16in;
else
notifyIcon.Icon = Properties.Resources.Icon16out;
iconIsOut = !iconIsOut;
}
lock (runCountLock)
{
threadRunning--;
}
});
}
}
// wait for all the threads to finish up
while (true)
{
lock (runCountLock)
{
if (threadRunning == 0)
break;
}
}
// set the notification icon to our default icon.
notifyIcon.Icon = Properties.Resources.Icon16;
}
// we're going down before we finished starting...
// oh well, be nice about it.
catch (ThreadAbortException) { }
}
【问题讨论】:
标签: c# multithreading threadpool