![](/img/trans.png)
[英]wpf what happens if ShowDialog() is called from a non-UI thread?
[英]Locking richtextboxes called from non-UI thread
給定以下代碼,我如何能夠鎖定richtextbox,以便每個日志調用在另一個可以開始鍵入之前完成工作?
private delegate void ReportLogDelegate(RichTextBox box, Color color, string message);
public void FileLog(string file, string project, string type, string fileNr, string note)
{
if (type == "incoming")
{
this.Invoke(new ReportLogDelegate(this.AppendText), new object[] { logTextBox, Color.Orange, String.Format("{0} - {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()) });
string message = string.Format("\n\tFile Incoming\n\tFile: {0}\n\tProject: {1}\n\tFileNumber: {2}\n\n", file, project, fileNr);
this.Invoke(new ReportLogDelegate(this.AppendText), new object[] { logTextBox, Color.White, message });
}
else if (type == "done")
{
this.Invoke(new ReportLogDelegate(this.AppendText), new object[] { logTextBox, Color.GreenYellow, String.Format("{0} - {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()) });
string message = string.Format("\n\tFile Received\n\tFile: {0}\n\tProject: {1}\n\tFileNumber: {2}\n\n", file, project, fileNr);
this.Invoke(new ReportLogDelegate(this.AppendText), new object[] { logTextBox, Color.White, message });
}
else if (type == "error")
{
this.Invoke(new ReportLogDelegate(this.AppendText), new object[] { logTextBox, Color.Red, String.Format("{0} - {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()) });
string message = string.Format("\n\tError Receiving File\n\tFile: {0}\n\tProject: {1}\n\tFileNumber: {2}\n\tError: {3}\n\n", file, project, fileNr, note);
this.Invoke(new ReportLogDelegate(this.AppendText), new object[] { logTextBox, Color.Red, message });
}
}
// Append text of the given color.
void AppendText(RichTextBox box, Color color, string text)
{
int start = box.TextLength;
box.AppendText(text);
int end = box.TextLength;
// Textbox may transform chars, so (end-start) != text.Length
box.Select(start, end - start);
{
box.SelectionColor = color;
// could set box.SelectionBackColor, box.SelectionFont too.
}
box.SelectionLength = 0; // clear
}
應該允許對FileLog的每次調用運行到最后,直到另一個可以訪問RTB。
只需將整個方法放入一個lock
塊中即可。 創建一個新的私有對象進行鎖定,以確保沒有其他方法可以使用相同的同步鎖定:
private object key = new object();
public void FileLog(string file, string project, string type, string fileNr, string note)
{
lock(key)
{
//your existing implementation goes here
}
}
這是假設您沒有其他方法也可以訪問該富文本框。 如果確實有其他對象,則需要確保所有對象都可以訪問您鎖定的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.