锁定从非ui线程调用的richtextbox



给定以下代码,我如何能够锁定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("ntFile IncomingntFile: {0}ntProject: {1}ntFileNumber: {2}nn", 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("ntFile ReceivedntFile: {0}ntProject: {1}ntFileNumber: {2}nn", 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("ntError Receiving FilentFile: {0}ntProject: {1}ntFileNumber: {2}ntError: {3}nn", 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
    }
}

这是假设您没有任何其他方法也将访问该富文本框。如果你有其他对象,那么你需要确保你锁定的对象对所有这些对象都是可访问的。

最新更新