异步方法正在阻止正在执行的UI线程 [英] async method is blocking UI thread on which it is executing

查看:63
本文介绍了异步方法正在阻止正在执行的UI线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Winform中考虑以下代码.当我单击按钮时,我期望async方法不应阻止正在其上执行的UI线程.

Consider the following codes in Winform. When I clicked the button, I was expecting that the async method should not block UI thread on which it was executing.

但是,我发现该按钮在异步方法调用期间被冻结... 如果为true,那么异步方法的意义是什么?我很困惑.

However, I found out that button was frozen during async method calling... If true, what is the point of async method? I am confused.

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

        async private void button1_Click(object sender, EventArgs e)
        {
            int contentlength = await AccessTheWebAsync();
            tbResult.Text =
                        string.Format("Length of the downloaded string: {0}.", contentlength);

            Debug.WriteLine(tbResult.Text);
        }    

        async Task<int> AccessTheWebAsync()
        {
            Debug.WriteLine("Call AccessTheWebAsync");
            Thread.Sleep(5000);
            Debug.WriteLine("Call AccessTheWebAsync done");
            tbResult.Text = "I am in AccessTheWebAsync";
            return 1000;
        }
    }
}

推荐答案

编译器警告会准确告诉您正在发生的事情:由于您的async方法从未使用过await,因此它将同步运行.

The compiler warning tells you exactly what's going on: since your async method does not ever await, it will run synchronously.

Thread.Sleep是同步操作;如果要伪造异步操作,请使用Task.Delay:

Thread.Sleep is a synchronous operation; if you want to fake an asynchronous operation, use Task.Delay:

async Task<int> AccessTheWebAsync()
{
  Debug.WriteLine("Call AccessTheWebAsync");
  await Task.Delay(5000);
  Debug.WriteLine("Call AccessTheWebAsync done");
  tbResult.Text = "I am in AccessTheWebAsync";
  return 1000;
}

这篇关于异步方法正在阻止正在执行的UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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