winforms 无法从C#上的特定线程中更改标签的属性(Windows窗体应用程序)[重复]

bfhwhh0e  于 2023-08-07  发布在  C#
关注(0)|答案(1)|浏览(114)

此问题在此处已有答案

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on(22答案)
5天前关闭。
我是C#的新手,所以请对我放松,但我遇到了一个问题,我无法更改我创建的线程中标签的可见性状态。
我尝试更改的标签名为DEBUG,与Label1没有任何关系
下面是表单的代码(DebugCount是在表单本身的代码中定义的整数):

public partial class GamePage : Form
    {
        public GamePage()
        {
            InitializeComponent();

            Thread DebugThread = new(new ThreadStart(DebugHandler));
            DebugThread.Start();
        }
        
        private void label1_Click(object sender, EventArgs e)
        {
            DebugCount++;
        }

        public void DebugHandler()
        {
            while(true)
            {
                if(DebugCount >= 5)
                {
                    DEBUG.Visible = true;
                    break;
                }
            }
        }
     }

字符串
以下是错误:System.InvalidOperationException:'跨线程操作无效:从创建控件“GamePage”的线程以外的线程访问该控件。

6yt4nkrj

6yt4nkrj1#

您可以将Control.Invoke()方法与MethodInvoker一起使用。它允许您在UI线程上执行来自另一个线程的代码段:

if (DebugCount >= 5)
{
    DEBUG.Invoke((MethodInvoker)delegate 
    {
        DEBUG.Visible = true;
    });
    break;
}

字符串

相关问题