c# - async await

Console:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication37
{
    class Program
    {
        public static Random R = new Random();
        public static string T { get; set; }

        static void Main(string[] args)
        {
            AsyncCall2();

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "exit")
                    break;
                Console.WriteLine(input.Length + " characters.");
            }

            Console.WriteLine("Press <Anykey> to exit application.");
            Console.ReadLine();
        }

        /// <summary>
        /// 无返回值的异步操作
        /// </summary>
        public static async void AsyncCall()
        {
            var t = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    // 随机睡0.1~0.3秒
                    int time = R.Next(1, 3) * 100;
                    Thread.Sleep(time);
                    Console.WriteLine("AsyncCall()=>" + Guid.NewGuid().ToString() + " cost " + time + " ms.");
                }
            });

            await t;
        }

        /// <summary>
        /// 调用有返回值异步操作
        /// </summary>
        public static async void AsyncCall2()
        {
            while (true)
            {
                T = await AsyncCallWithReturn();
                Console.WriteLine(T);
            }
        }

        /// <summary>
        /// 有返回值异步操作
        /// </summary>
        /// <returns></returns>
        public static async Task<string> AsyncCallWithReturn()
        {
            // 等待结束
            return await Task.Factory.StartNew<string>(() =>
            {
                // 随机睡1~5秒
                int time = R.Next(1, 5) * 1000;
                Thread.Sleep(time);
                return "AsyncCallWithReturn()=>" + Guid.NewGuid().ToString() + " cost " + time + " ms.";
            });
        }
    }
}

Winform:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label1;

        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            this.label1.Text = this.textBox1.Text.Length + " characters.";
            var text = await AsyncCall();
            this.label1.Text = text;
        }

        private async Task<string> AsyncCall()
        {
            return await Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                return Guid.NewGuid().ToString();
            });
        }

        #region AutoGenerated Code

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(46, 38);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Set";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(46, 12);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(356, 20);
            this.textBox1.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(46, 68);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(0, 13);
            this.label1.TabIndex = 2;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(529, 103);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        #endregion
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值