码迷,mamicode.com
首页 > Web开发 > 详细

.net async await

时间:2016-06-27 19:22:54      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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;
            }
        }

    }
}

 

.net async await

标签:

原文地址:http://www.cnblogs.com/daixingqing/p/5620868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!