首页 > 解决方案 > 如何更改 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

标签: c#multithreadingwinforms

解决方案


试试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
}

推荐阅读