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线程接收消息
  • 相关阅读:
    Randomization Tests
    关于Spring中的<context:annotationconfig/>配置
    PUT method support
    在对话框picture control中利用opengl进行绘图
    【学习笔记】《卓有成效的管理者》 第三章 我能贡献什么
    程序员的黄金时代
    nginx webdav配置
    iphone4s 如何强制关机
    并查集
    实战虚拟化存储设计之三MultiPathing
  • 原文地址:https://www.cnblogs.com/sdikerdong/p/4398961.html
Copyright © 2011-2022 走看看