C# Task.FromResult获取Task执行后的返回值或对象

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //需要下载的url集合
            string[] urls = new string[] {
                "https://www.cnblogs.com",
                "https://www.baidu.com",
                "https://www.bing.com/"
            };
 
            //用于计时下载操作
            Stopwatch stopwatch = new Stopwatch();
            //开始计时下载url所需要的时间
            stopwatch.Start();
            var downloads = from url in urls
                            select CachedDownloads.DownloadStringAsync(url);
            Task.WhenAll(downloads).ContinueWith(results =>
            {
                stopwatch.Stop();
                //打印下载的字符数和运行时间。
                Console.WriteLine("First Time Retrieved {0} characters. Elapsed time was {1} ms.",
                  results.Result.Sum(result => result.Length),
                  stopwatch.ElapsedMilliseconds);
            }).Wait();
 
 
            //重新计时
            stopwatch.Restart();
            downloads = from url in urls
                        select CachedDownloads.DownloadStringAsync(url);
            Task.WhenAll(downloads).ContinueWith(results =>
            {
                stopwatch.Stop();
                //打印下载的字符数和运行时间。
                Console.WriteLine("Second Time Retrieved {0} characters. Elapsed time was {1} ms.",
                   results.Result.Sum(result => result.Length),
                   stopwatch.ElapsedMilliseconds);
            }).Wait();
 
            Console.ReadKey();
        }
    }
 
    class CachedDownloads
    {
        /// <summary>
        /// 将下载在操作的结果保存在线程安全集合cachedDownloads中
        /// </summary>
        static ConcurrentDictionary<string, string> cachedDownloads = new ConcurrentDictionary<string, string>();
 
        /// <summary>
        /// 以字符串的形式异步下载所请求的资源
        /// </summary>
        /// <param name="address">地址</param>
        /// <returns></returns>
        public static Task<string> DownloadStringAsync(string address)
        {
            //首先尝试从缓存中检索内容。
            string content;
            //如果结果在缓存中,则直接返回
            if (cachedDownloads.TryGetValue(address, out content))
            {
                return Task.FromResult<string>(content);
            }
            //如果结果不在缓存中,那么使用异步方法下载字符串,并将其添加到缓存中
            return Task.Run(async () =>
            {
                content = await new WebClient().DownloadStringTaskAsync(address);
                cachedDownloads.TryAdd(address, content);
                return content;
            });
        }
    }
}

MSCL超级工具类库
基于C#开发的超强工具类,包含数据库操作,字符串处理,文件或者文件夹处理
网络请求,缓存处理,数据容器等上百个常用工具类封装,附带调用示例和参数说明,
提供CHM详细文档,上百个生产环境使用,稳定高效,简单易用。
真正做到“工具在手,一切尽有”,让你大幅度的提高编程效率,提高编程水平。
联系QQ:7400799(请备注 "MSCL")

===============================================

重要压缩文件忘记解压密码?网上下载rar/zip/7z等压缩文件,需要密码?
====极速解密助手,支持支持RAR/ZIP/7Z等多种压缩文档解密======
★ 解密不超过24小时,跟密码复杂程度相关
★ 解密成功后再收费,无套路
★ 解密成功后自动删除原件,无后顾之忧
联系QQ:7400799(请备注 "文件解密")

==============================================

Magic.Orm已在数百个成熟项目中应用,是比较完善的ORM框架(基于C#开发)。开发过程中参考了NBear与MySoft,吸取了其中的一些精华,加入新思想,
后期参考EF的Lambda语法进行大量扩展。

为什么选择Magic.Orm?

  • 上手简单,0学习成本。使用方便,按照sql书写习惯编写C#.NET代码。功能强大。
  • 高性能,接近手写Sql。
  • 体积小(不到200kb,仅一个dll)。
  • 完美支持Sql Server(2000至最新版),MySql,Oracle,Access,Sqlite等数据库。
  • 支持大量Lambda表达式写法。
  • 不需要像NHibernate的XML配置,不需要像EF的各种数据库连接驱动,集成简单。

购买源码 请联系QQ:7400799(请备注 "ORM")

原文地址:https://www.cnblogs.com/smartsmile/p/14416005.html