gpt4 book ai didi

c# - 在单独的线程上运行自己的类

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:00 24 4
gpt4 key购买 nike

我想在另一个线程中运行自己的类,但如果这样做,我就不能在 EventHandler 中使用我的标签,我该如何避免呢?

这就是我的代码的样子:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ts3_Movearound
{
public partial class Form1 : Form
{
TS3_Connector conn = new TS3_Connector();
Thread workerThread = null;
public Form1()
{
InitializeComponent();
conn.runningHandle += new EventHandler(started);
conn.stoppedHandle += new EventHandler(stopped);
}

private void button1_Click(object sender, EventArgs e)
{
//System.Threading.Thread connw = new System.Threading.Thread(conn);
workerThread = new Thread(conn.Main);
workerThread.Start();
}

public void started(Object sender, EventArgs e)
{
label1.Text = "Status: Running!";
}
public void stopped(Object sender, EventArgs e)
{
label1.Text = "Status: Stopped!";
}
}
}

这就是错误:

InvalidOperationExpetion in Line "label1.Text = "Status: Running!";"

最佳答案

您只能通过 UI 线程更新控件。使用 label1.Invoke() 来做到这一点:

label1.Invoke((MethodInvoker)delegate {
label1.Text = "Status: Running!";"
});

关于c# - 在单独的线程上运行自己的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13135915/

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