使用异步编程实现一个加法运算

加法用法 :两个数先后生成,生成这两个数给随机的延迟,等两个数都生成完后再计算结果

 public MainWindow()
        {
            InitializeComponent();
        }
        Random rnd = new Random();
        int aa, bb, cc;
        public async Task GetA()
        {
            await Task.Run(async () =>
             {

                 await Task.Delay(rnd.Next(1000));
                 aa = rnd.Next(100);
             });
            a.Text = aa.ToString();
        }
        public async Task GetB()
        {
            await Task.Run(async () =>
            {

                await Task.Delay(rnd.Next(1000));
                bb = rnd.Next(100);
            });
            b.Text = bb.ToString();
        }
        public async Task GetResult()
        {
            await Task.WhenAll(GetB(), GetA());
            c.Text = (aa + bb)+"";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            a.Text = b.Text = c.Text = "";
            GetResult();
        }
    }

 

posted @ 2017-04-13 18:50  lunawzh  阅读(531)  评论(0编辑  收藏  举报