我猜你想要做的是創建子線程做的工作不阻塞UI線程(僞代碼,又名未測試):
public void button2_Click(object sender, EventArgs e)
{
// Copy text in a non-thread protected string, to be used within the thread sub-routine.
string searchText = textBox3.Text;
string contentText = dragDropRichTextBox1.Text;
// Create thread routine
ThreadPool.QueueUserWorkItem(o => {
// Iterate through all instances of the string.
int index = 0;
while (index < contentText.LastIndexOf(searchText))
{
dragDropRichTextBox1.Invoke((MethodInvoker) delegate {
// Update control within UI thread
//Highlight text when search button is clicked
dragDropRichTextBox1.Find(searchText, index, contentText.Length, RichTextBoxFinds.None);
dragDropRichTextBox1.SelectionBackColor = Color.Orange;
}
// Go to next instance
index = contentText.IndexOf(searchText, index) + 1;
}
});
}
再次,這是未經測試,但會給你的想法。
- 編輯 -
你不需要線程可言,做一個dragDropRichTextBox1.SuspendLayout()
和dragDropRichTextBox1.ResumeLayout()
之間所有的工作就足夠了。
private void button1_Click(object sender, EventArgs e)
{
// Copy text in a non-thread protected string, to be used within the thread sub-routine.
string searchText = textBox1.Text;
string contentText = richTextBox1.Text;
// Suspend all UI refresh, so time won't be lost after each Find
richTextBox1.SuspendLayout();
// Iterate through all instances of the string.
int index = 0;
while (index < contentText.LastIndexOf(searchText))
{
//Highlight text when search button is clicked
richTextBox1.Find(searchText, index, contentText.Length, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Orange;
// Go to next instance
index = contentText.IndexOf(searchText, index) + 1;
}
// Finally, resume UI layout and at once get all selections.
richTextBox1.ResumeLayout();
}
這裏所有的實際工作都是由richtextbox本身完成的,因此99%的CPU將用於UI線程。沒有必要只是圍繞一個調用包裝一個線程。 – Blorgbeard 2015-02-09 20:43:27
我認爲他的問題的重點是如何將該工作移動到後臺線程中,以便在搜索功能運行時UI不會掛起。使用後臺線程來調用UI線程來完成所有工作並不會改善用戶體驗,這似乎是這裏的目標。 – Levesque 2015-02-10 19:46:56