.net async await

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace CookBook
{
    class Program
    {
        static void Main(string[] args)
        {
            //Class1 class1 = new Class1();
            //Console.WriteLine("主线程开始");
            //class1.DoSomethingAsync();
            //Console.WriteLine("主线程结束");


            //Class2 class2 = new Class2();
            //Console.WriteLine("主线程开始");
            //class2.DoSomethingAsync();
            //Console.WriteLine("主线程结束");

            //string info = Class3.GetUrlStr("http://www.baidu.com");
            //Console.WriteLine(info);



            Console.WriteLine("1主线程开始:{0}", Thread.CurrentThread.ManagedThreadId);
            Program p = new Program();
            string url = "http://www.baidu.com";
            int timeout = 1;

            p.DoSomethingAsync(url, timeout);

            p.DoSomething();


            Console.WriteLine("6主线程结束:{0}", Thread.CurrentThread.ManagedThreadId);

            Console.ReadKey();
        }

        public async Task DoSomethingAsync(string url, int timeout)
        {
            Console.WriteLine("2子线程开始:{0}", Thread.CurrentThread.ManagedThreadId);
            try
            {
                var result = await DownloadStringWithRetries(url, timeout);
                Console.WriteLine("{0}", result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("7错误:{1},{0}", Thread.CurrentThread.ManagedThreadId, ex.Message);
            }
            Console.WriteLine("4子线程结束:{0}", Thread.CurrentThread.ManagedThreadId);
        }

        private void DoSomething()
        {
            Console.WriteLine("3主线程开始:{0}", Thread.CurrentThread.ManagedThreadId);
            for (int j = 0; j != 1000; j++)
            {
                int result = 0;
                for (int i = 0; i != 10000000; i++)
                {
                    result *= i;
                }
            }
            Console.WriteLine("5主线程开始:{0}", Thread.CurrentThread.ManagedThreadId);
        }
        /// <summary>
        /// 获取url源码,报错重试
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private async Task<string> DownloadStringWithRetries(string url, int timeout)
        {
            var nextDelay = TimeSpan.FromSeconds(1);
            for (int i = 0; i != 3; ++i)
            {
                try
                {
                    return await DownloadStringWithTimeout(url, timeout);
                }
                catch
                {
                }
                await Task.Delay(nextDelay);
                nextDelay = nextDelay + nextDelay;
            }
            return await DownloadStringWithTimeout(url, timeout);
        }
        /// <summary>
        /// 获取url源码,超时直接报错
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private async Task<string> DownloadStringWithTimeout(string url, int timeout)
        {
            using (var client = new HttpClient())
            {
                var downloadTask = client.GetStringAsync(url);
                var timeoutTask = Task.Delay(timeout);

                var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
                if (completedTask == timeoutTask)
                {
                    throw new Exception("处理超时");
                }
                return await downloadTask;
            }
        }

    }
}

 

posted @ 2016-06-27 17:42  一千零一夜  阅读(163)  评论(0编辑  收藏  举报