并不是说我不欣赏多线程ThreadPool
或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) { }
}