欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.Net异步编程之Async与Await的使用

程序员文章站 2024-01-04 11:07:46
...

1.同步

 private void button1_Click(object sender, EventArgs e)
        {
            this.label1.Text = DoWork();
        }
        private string DoWork()
        {
            Thread.Sleep(5000);
            return "StartDo";
        }

2.异步(有返回值)

private async void button2_Click(object sender, EventArgs e)
        {
            this.label1.Text = await DoWorkAsync();
        }
        private Task<string> DoWorkAsync()
        {
            return Task.Run(() => {
                Thread.Sleep(5000);
                return "StartDo";
            });
        }

3.异步(无返回值)

 private async void button3_Click(object sender, EventArgs e)
        {
            await Task.Run(() => 
            { 
                Thread.Sleep(3000);
                MessageBox.Show("StartDo");
            });
        }

4.具有多个await的异步方法

private async void button4_Click(object sender, EventArgs e)
        {
            await Task.Run(() =>{ Thread.Sleep(3000);});
            MessageBox.Show("1");

            await Task.Run(() => { Thread.Sleep(3000); });
            MessageBox.Show("2");

            await Task.Run(() => { Thread.Sleep(3000); });
            MessageBox.Show("3");
        }

参考教程

http://www.cnblogs.com/x-xk/archive/2013/06/05/3118005.html

http://www.cnblogs.com/tdws/p/5679001.html

http://www.cnblogs.com/liqingwen/p/5831951.html

http://www.cnblogs.com/liqingwen/p/5831951.html

上一篇:

下一篇: