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線程接收消息
相關文章
相關標籤/搜索