异步任务中的 C# 更改标签文本

标签 c# user-interface asynchronous label 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
    }

如果您可以将 async 与 UI 一起使用,那将非常方便

最佳答案

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

async的设计精心制作,因此您可以在 UI 中自然地使用它。

in my code i run a function that does a lot of IO and stuff that takes a long time

如果你有异步 I/O 方法(你应该有),那么你可以这样做:

private async void button1_Click(object sender, EventArgs e)
{
  label1.Text = "Test";
  await MyMethodAsync();
}

public async Task MyMethodAsync()
{
  label1.Text = "";
  await ...; // "lot of IO and stuff"
  label1.Text = "Done";
}

这是最自然的方法。

但是,如果您需要在后台线程上运行代码(例如,它实际上受 CPU 限制,或者您只是不想让 I/O 操作像它们应该的那样异步是),那么你可以使用 IProgress<T> :

private void button1_Click(object sender, EventArgs e)
{
  label1.Text = "Test";
  var progress = new Progress<string>(update => { label1.Text = update; });
  await Task.Run(() => MyMethod(progress));
}

public void MyMethod(IProgress<string> progress)
{
  if (progress != null)
    progress.Report("");
  ...; // "lot of IO and stuff"
  if (progress != null)
    progress.Report("Done");
}

现代代码在任何情况下都不应使用 Control.Invoke或者(更糟)Control.InvokeRequired .

关于异步任务中的 C# 更改标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281387/

相关文章:

javascript - jQuery - 使用全局数组并等待 $get 加载检索到的数据?

C# Datagridview - 检查行是否被选中

c++ - 实现缩放 slider QGraphicsView

java - GWT 的各种异步设施

javascript - 如何创建类似滚动 UI 的 Google Plus?

java - 使用箭头键浏览 JButton

.net - Socket 异步发送和接收数据

c# - 在 .net c# 代码中创建类类型

c# - 将具有空值的参数添加到 sqldatasource 控件的更好方法

c# - 为什么即使设置了 RecordSelectionFormula, Crystal 报表也会获取所有记录?