以下代码不改变文本并停止执行任务
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/