gpt4 book ai didi

c# - 锁定从非 UI 线程调用的富文本框

转载 作者:行者123 更新时间:2023-11-30 20:57:49 26 4
gpt4 key购买 nike

给定以下代码,我如何能够锁定 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
}

在另一个访问 RTB 之前,应允许对 FileLog 的每次调用运行到结束。

最佳答案

只需将整个方法体放入一个lock block 中即可。创建一个新的私有(private)对象来锁定,这样你就可以确定没有其他方法在使用相同的同步锁:

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
}
}

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

关于c# - 锁定从非 UI 线程调用的富文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16526303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com