编辑:它不是一个列表框。我的错。这是一个列表视图。使用线程来统计C#事件中的循环
我有一个列表视图控件,这让我疯狂。这是一个多选列表框,所以如果用户选择5000行,然后通过选择单行来取消选择它们,则SelectedIndexChanged将触发5001次。这会导致我的应用程序挂起。
我正在尝试使用线程来统计事件已经触发的次数,然后让最后一次迭代完成所有实际的工作。
这是我开始的代码。 大问题:由于项目超出我的控制范围,我需要“做花哨的计算”与呼叫事件处于同一线程。
编辑:我知道,这段代码不起作用。 Join()阻止当前线程,否定了创建线程的全部目的。我的问题是:我如何做这样的事情。
我最大的问题是没有创建线程。这就是我的“看中”必须在同一个线索。
void IncrPaintQueue()
{
PaintQueue++;
Thread.Sleep(100);
}
int PaintQueue = 0;
private void SegmentList_SelectedIndexChanged(object sender, EventArgs e)
{
// We need to know how many threads this may possibly spawn.
int MyQueue = PaintQueue;
// Start a thread to increment the counter.
Thread Th = new Thread(IncrPaintQueue);
Th.IsBackground = true;
Th.Start();
Th.Join();
// if I'm not the last thread, then just exit.
// The last thread will do the right calculations.
if (MyQueue != PaintQueue - 1)
return;
// Reset the PaintQueue counter.
PaintQueue = 0;
// ... do fancy calculations here...
}
你在使用什么平台?这是一个Windows窗体应用程序? – 2009-01-22 18:03:14
它不能是winforms,因为windows窗体中的ListBox控件的行为不像解释的那样。选择单个项目以取消选择倍数只会触发一个SelectedIndexChanged事件。 – 2009-01-22 18:08:51
是的。它是winForms。我编辑了这篇文章。感谢您的支持。 – Jerry 2009-01-22 18:12:11