When you use Task.Run()
, you're saing that you don't want the code to run on the current context, so that's exactly what happens.
But there is no need to use Task.Run()
in your code. Correctly written async
methods won't block the current thread, so you can use them from the UI thread directly. If you do that, await
will make sure the method resumes back on the UI thread.
This means that if you write your code like this, it will work:
private async void button1_Click(object sender, EventArgs e)
{
await Run();
}
private async Task Run()
{
await File.AppendText("temp.dat").WriteAsync("a");
label1.Text = "test";
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…