异步任务中的C#更改标签文本 [英] C# in Async Task change Label Text

查看:102
本文介绍了异步任务中的C#更改标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不会更改文本并停止执行任务

The following Code does not change the Text and stops executing the Task

private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "Test";
        Task.Run(() => MyAsyncMethod());
    }

    public async Task MyAsyncMethod()
    {
        label1.Text = "";
        //everything from here on will not be executed
    }

如果您可以将异步与UI一起使用,

would be really handy if you could use async together with the UI

推荐答案

,用于通过您需要调用的第二个线程访问GUI控件. 以下示例显示了如何正确设置标签文本

for accessing a GUI control through a second thread you need to invoke. following example shows how to set a label's text properly

  private void setLabel1TextSafe(string txt)
  { 
       if(label1.InvokeRequired)
           label1.Invoke(new Action(() => label1.Text = txt));
       else
           label1.Text = txt;
  }

我希望这可以解决您的问题

I hope this solves your problem

这篇关于异步任务中的C#更改标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆