zoukankan      html  css  js  c++  java
  • await, anync

    public Form1()
            {
                InitializeComponent();
            }
    
            // The following method runs asynchronously. The UI thread is not
            // blocked during the delay. You can move or resize the Form1 window 
            // while Task.Delay is running.
            public async Task<string> WaitAsynchronouslyAsync()
            {
                await Task.Delay(10000);
                MessageBox.Show("fi");
                return "Finished";
            }
    
            // The following method runs synchronously, despite the use of async.
            // You cannot move or resize the Form1 window while Thread.Sleep
            // is running because the UI thread is blocked.
            public async Task<string> WaitSynchronously()
            {
                // Add a using directive for System.Threading.
                Thread.Sleep(10000);
                return "Finished";
            }
    
            private async void button1_Click_1(object sender, EventArgs e)
            {
                string result = string.Empty;
                WaitAsynchronouslyAsync();
    
                // Call the method that runs asynchronously.
                //result = await WaitAsynchronouslyAsync();
                // Call the method that runs synchronously.
                // result = await WaitSynchronously ();
    
                // Display the result.
                textBox1.Text += result;
                MessageBox.Show("hi");
            }
    上述代码得出至少两点:
    1. await WaitAsynchronouslyAsync() 执行时要等待这个调用完成,才会执下后面的代码,但在这个调用没有完成前,其thread是可以被其它代码占用的,表现就是UI仍可以接收其它消息
    2. WaitAsynchronouslyAsync()函数执行的线程与UI主线程是同一个,这也是为什么在这个函数中的messagebox可以显示,Thread.sleep可以阻止UI线程接收消息
  • 相关阅读:
    c语言 判断文件是否存在
    lua 二进制函数使用
    linux sort 多列正排序,倒排序
    free命令学习 输出理解
    nginx 配置实现逻辑预算
    nginx 使用ctx实现数据共享,修改上下文
    lua中的数学库
    tornado文件上传实例
    ajax技术初识与应用
    web框架--XSS攻击和CSRF请求伪造
  • 原文地址:https://www.cnblogs.com/sdikerdong/p/4398961.html
Copyright © 2011-2022 走看看