c# - 如何更改 label.text 使用 Task.Run()
问题描述
没有工作await Task.Run()
:
private async void button2_Click(object sender, EventArgs e)
{
await Task.Run(() => {
monitor_r(label1);
});
}
protected async Task monitor_r(Label L1)
{
MessageBox.Show(L1.Name);
L1.ForeColor = Color.Blue;
L1.Text = "test";
}
这些命令
MessageBox.Show(L1.Name);
和
L1.ForeColor = Color.Blue;
工作正常,但
L1.Text = "test";
不工作。
你能帮忙吗,为什么不换一个Label Text
?
解决方案
试试Control.Invoke :我们应该只在主线程中运行 Winform UI
protected async Task monitor_r(Label L1)
{
Action action = () =>
{
MessageBox.Show(L1.Name);
L1.ForeColor = Color.Blue;
L1.Text = "test";
};
if (L1.InvokeRequired)
L1.Invoke(action); // When in different thread
else
action(); // When in the main thread
}
推荐阅读
- shell - 在shell函数中调用命令时如何防止?
- c++ - 使用 SDL2 和 OpenGL 旋转相机和三角形绘制不会显示任何东西?
- c - 找到一个等于输入的字符
- javascript - 如何添加到变量 javascript 的现有值?
- c++ - 使用 decltype(lambda) 的 C++/可变参数模板和参数包
- rust - 包装任意数量类型的宏
- swift - 无法强制解开值
- javascript - JavaScript html Textarea无法读取null的属性'1'
- javascript - 多个 dropzone.js css 样式
- operating-system - 如何编写适用于不同操作系统的程序?