假设我有 2 个类:Form1.cs
和 Step.cs
在 Form
类中,我调用了 Step
类的方法并将其分配到新线程上,避免与 UI 发生冲突。
Form1.cs
public partial class Form1 : Form
{
Step test_step = new Step();
public void main_run_auto() {
test_step.TakeAction();
}
public void function_1() {
Thread thread_1 = new Thread(() => main_run_auto());
thread_1.start();
}
}
步骤.cs
public class Testing_Steps_class
{
public void TakeAction() {
string status = "";
// Step 1
...do something...
status = "Updated Stt 1";
// Step 2
...do something...
status = "Updated Stt 2";
// Step 3
...do something...
status = "Updated Stt 3";
}
}
我的问题是:如何在类 Form1
中的文本框或数据 GridView 行上立即更新变量状态?
谢谢。
最佳答案
您不能从其他线程访问在 UI
线程上创建的控件。您必须使用 Invoke
或 BeginInvoke
来更改 UI
。
public void TakeAction() {
// Step 1
...do something...
UpdateUI("Updated Stt 1");
// Step 2
...do something...
UpdateUI("Updated Stt 2");
// Step 3
...do something...
UpdateUI("Updated Stt 3");
}
void UpdateUI(string message)
{
Textbox1.Invoke((MethodInvoker)(() =>
{
textbox1.Text= message;
}));
}
关于c# - 如何从其他类的独立线程上运行的方法中获取变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563580/