gpt4 book ai didi

c# - 在另一个线程上访问数据

转载 作者:太空宇宙 更新时间:2023-11-03 17:59:23 25 4
gpt4 key购买 nike

我有一个 winform 和一些线程。当我尝试从其中一个线程访问 winform 中的字段时,出现以下错误: 跨线程操作无效:从创建它的线程以外的线程访问控件“richTextBox1”。

我该如何解决这个问题?

问候,亚历山德鲁·巴德斯库

最佳答案

所有控件都有一个名为 Invoke 的方法,该方法将委托(delegate)作为第一个参数和可选的params object[]
您可以轻松地使用此方法:

richTextBox1.Invoke(new MethodInvoker(DoSomething));  

在哪里

void DoSomething()
{
richTextBox1.BackColor = Color.Cyan;
}

委托(delegate) MethodInvoker 位于 System.Windows.Forms 命名空间中,我想您已经在使用它了。

您甚至可以从同一个线程调用!

你也可以使用参数,像这样:

richTextBox1.Invoke(new ColorChanger(DoSomething), Color.Cyan);  

在哪里

delegate void ColorChanger(Color c);

void DoSomething(Color c)
{
richTextBox1.BackColor = c;
}

希望对您有所帮助!

编辑:
InvokeRequired 如果您从一个...基本上...未知线程使用相同的方法,则需要该方法。所以它看起来像这样:

void DoSomething()
{
if (richTextBox1.InvokeRequired)
richTextBox1.Invoke(new MethodInvoker(DoSomething));
else
{
richTextBox1.BackColor = Color.Cyan;
// Here should go everything the method will do.
}
}

您可以从任何线程调用此方法!

对于参数:

delegate void ColorChanger(Color c);

void DoSomething(Color c)
{
if (richTextBox1.InvokeRequired)
richTextBox1.Invoke(new ColorChanger(DoSomething), c);
else
{
richTextBox1.BackColor = c;
// Here should go everything the method will do.
}
}

享受编程吧!

关于c# - 在另一个线程上访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062993/

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