を使用してファイルリスナー(txtファイル用)で作業しており、FileSystemWatcher
すべての新しい行をに追加したいと考えていますRichTextBox
。新しいテキストをリッチテキストにフォーマットするには多くのCPUパワーが必要なので、これにはBackgroundWorkerを使用することにしました。
プログラムはまだ動作していますが、MSWindowsをロックして再ログインするとフォームがハングします。BackgroundWorkerスレッドがUIスレッドをブロックしているようです。AppendTexttoRichTextBoxBeginInvoke
の代わりに使用する他の効果はありません。Invoke
フォーマットされていないテキストをすべてに渡すと、e.Result
正常に機能していbw_DoWork
ます(ブロッキングスレッドはありません)。一時的なRichTextBoxはメインフォームに添付されていません。「ハング」の問題を解決するにはどうすればよいですか?
コードサンプルの前のロジック:FileSystemWatcher
イベントChanged
が開始しBackgroundWorker.RunWorkerAsync
ます。
StringBuilder unformattedText;
private void bw_DoWork( object sender, DoWorkEventArgs e )
{
// Write all new lines for this file to
// StringBuilder variable unformattedText
ReadFromFile (...)
// Need a temporary RichTextBox to create new formatted text
RichTextBox tempRtb = new RichTextBox();
// Split new unformatted text with regex, format some tokens
// and append each to temporary RichTextBox tempRtb
HighlightWords( tempRtb, unformattedText );
e.Result = tempRtb.Rtf;
}
private void bw_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e )
{
string rtfText = e.Result as string;
// Append text to main RichTextBox
if (rtb.InvokeRequired)
{
rtb.BeginInvoke(
new MethodInvoker( delegate
{
AppendRichText( rtb, rtfText );
} ) );
}
else
{
AppendRichText( rtb, rtfText );
}
}
private void AppendRichText(RichTextBox rtb, string text)
{
// Append formatted text at the end of the RichTextBox
rtb.Select( rtb.TextLength, 0 );
rtb.SelectedRtf = text;
rtb.ScrollToCaret();
}
注:これらは、問題を理解するためのコード部分にすぎません。完全ではありません。