我有一個小應用程序,讀取管道delimted文件並寫出線的RTB,強調如果有dissallowed在一定的「列」字從BackgroundWorker的一個RichTextBox。這是完美的工作......但是,用戶需要一個進度條,並且看到正在寫入的行「實時」,並且能夠在中途取消。如何更新使用的BeginInvoke
我有一直在使用寫入到一個RichTextBox,同時阻擋UI以下擴展方法,但是這種失敗使用具有BeginInvoke的一個BackgroundWorker。
的失敗是查找文本的當前長度時。
public static void AppendLine(this RichTextBox richTextBox, string text, List<Char> foundChars, List<int> columns)
{
var split = text.Trim().Split(new char[] { '|' });
for (int i = 0; i < split.Count(); i++)
{
**var start = richTextBox.TextLength;**
richTextBox.AppendText(split[i]);
var end = richTextBox.TextLength;
if (columns.Contains(i + 1))
{
foreach (var foundChar in foundChars)
{
var current = start;
while (current > 0)
{
var position = richTextBox.Find(new char[] { foundChar }, current, end);
current = position + 1;
if (current > 0)
{
richTextBox.Select(position, 1);
richTextBox.SelectionColor = Color.Red;
}
}
}
}
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = Color.Black;
}
richTextBox.AppendLine();
}
private void UpdateResultsLine(string line, List<char> foundChars)
{
if (txtResults.InvokeRequired)
{
txtResults.BeginInvoke(new UpdateResultsLineDelegate(UpdateResultsLine), line, foundChars);
}
txtResults.AppendLine(line, foundChars, _fileType.ProcessColumns);
}
但是,如果我叫任何/所有以同樣的方式這些擴展的,他們的工作?
public static void AppendLine(this RichTextBox richTextBox)
{
richTextBox.AppendText(Environment.NewLine);
}
public static void AppendLine(this RichTextBox richTextBox, string text)
{
richTextBox.AppendText(text + Environment.NewLine);
}
public static void AppendLine(this RichTextBox richTextBox, string text, params object[] args)
{
richTextBox.AppendLine(string.Format(text, args));
}
我在想什麼?還是有另一種方法可以將彩色文字寫入RTB?
使用'BackgroundWorker'組件的一點是,你在更新了'ProgressChanged'和/或'RunWorkerCompleted'事件處理方法的UI。你根本不需要使用'BeginInvoke'。請參閱MSDN上的示例[此處](http://msdn.microsoft.com/zh-cn/library/system.componentmodel.backgroundworker.aspx)。 –
對不起,但這並不符合我的全部要求。我需要更新一個以上的RTB,另外可能還有一個標籤和進度條。是的,我可以創建一個新的對象來傳遞,包含一個Enum來說明需要更新哪些內容並切換到每個ProgressChanged調用中,但這似乎過分了。 – BlueChippy
我不明白你爲什麼不能更新'ProgressChanged'事件處理器方法中的多個控件。你不需要創建任何對象或傳遞它們。處理這些事件的關鍵是它們在UI線程中引發。 –