访问UI控件在Task.Run与异步/等待上的WinForms [英] Accessing UI controls in Task.Run with async/await on WinForms

查看:225
本文介绍了访问UI控件在Task.Run与异步/等待上的WinForms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个按钮和一个标签的WinForms应用程序下面的code:

I have the following code in a WinForms application with one button and one label:

using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            await Run();
        }

        private async Task Run()
        {
            await Task.Run(async () => {
                await File.AppendText("temp.dat").WriteAsync("a");
                label1.Text = "test";
            });    
        }
    }
}

这是我工作的实际应用的简化版本。我是IM pression中,通过使用异步/等待下我的 Task.Run 我可以设置 label1.Text 属性。然而,在运行此code时,我得到了我不是UI线程上的错误,我无法访问控制。

This is a simplified version of the real application I'm working on. I was under the impression that by using async/await in my Task.Run I could set the label1.Text property. However, when running this code I get the error that I'm not on the UI thread and I can't access the control.

为什么我不能访问标签控件?

Why can't I access the label control?

推荐答案

当您使用 Task.Run(),你saing你的别ŧ的希望code到当前上下文中运行,所以这正是发生。

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.

但也没有必要在你的code使用 Task.Run()。正确写入异步方法将不会阻止当前线程,这样你就可以从UI线程中直接使用它们。如果你这样做,等待将确保该方法恢复回UI线程上。

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.

这意味着,如果你写你的code这个样子,这将工作:

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";
}

这篇关于访问UI控件在Task.Run与异步/等待上的WinForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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