![](/img/trans.png)
[英]A thread for updating a RichTextBox.Text twice a second is not working
[英]Get richtextbox.text from another thread
我不敢相信以前沒有問過這個問題,但是我在這里找不到參考。 對不起,如果我錯過了! 從線程更新rtb.Text有很多,但是獲取rtb.Text很少或沒有。
我需要從另一個線程從UI線程上的richtextbox獲取文本值,然后才能遍歷同一richtextbox的每一行。
我想需要調用和代表,但如何制作它們?
作為示例,如果代碼在同一線程中,則將類似於:
private void checkRtbEntries()
{
if (rtb.Text != "")
{
foreach (string textLine in rtb.Lines)
{
// do some things in the background thread
// based on the rtb line content...
}
}
}
但是,從Backgroundworker線程內部調用checkRtbEntries(),而rtb在UI線程中,因此拋出了無效的跨線程操作。
運行BackgroundWorker線程時,可以選擇向其傳遞參數,其他線程可以引用並使用該參數:
myWorker.RunWorkerAsync(rtb.Text);
在DoWork
事件中,將參數DoWork
回字符串並對其執行操作。
var myRtbText = e.Argument.ToString();
這樣,您的后台線程實際上就不會觸及UI線程。
如果您需要更改的元素背面的主線程上,而你的背景工人正在運行,你需要使用ProgressChanged
事件。
由於在DoWork
事件中沒有對RichTextBox
的引用(僅是其Text
屬性的內容),因此您實際上無法在原始文本框中調用Lines
屬性。
不過,您應該能夠輕松地對其進行仿真(實際的Lines
屬性會測試“ \\ r”,“ \\ r \\ n”和“ \\ n”,但是Environment.NewLine
應該為您確定這一點):
var allLines
= myRtbText.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
(或者,如果您想忽略空白行,請使用StringSplitOptions.RemoveEmptyEntries。)
這是從后台跳轉到UI線程的常用方法(對於每個控件)
private delegate void checkRichTextBoxDelegate();
private void checkRtbEntries()
{
if (this.rtb.InvokeRequired)
{
checkRichTextBoxDelegate checkEntries = new checkRichTextBoxDelegate(checkRtbEntries);
this.Invoke(checkRtbEntries);
}
else
{
.... do your work on the RichTextBox, you are on the UI thread
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.