編輯:它不是一個列表框。我的錯。這是一個列表視圖。使用線程來統計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