如何使用Task.FromResult?

Task.FromResult

字数:889字

预计阅读时间:3分钟

1.解释

官方定义:创建一个结果的、成功完成的Task<TResult>

public static System.Threading.Tasks.Task<TResult> FromResult<TResult> (TResult result);

可以看出,Task.FromResult( )方法接受一个TResult然后返回一个Task<TResult>

2.例子

使用 Task.FromResult方法检索缓存中保存的异步下载操作的结果。

Ex:

​ 以下示例从Web下载字符串。它定义了DownloadStringAsync方法。此方法异步从Web下载字符串。此示例还使用ConcurrentDictionary <TKey,TValue>对象来缓存先前操作的结果。如果输入地址保存在此缓存中,则DownloadStringAsync使用FromResult方法生成一个Task <TResult>对象,该对象保存该地址的内容。否则,DownloadStringAsyncWeb下载文件并将结果添加到缓存中。

1.添加CachedDownloads类,并且定义方法

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

​ 该类定义了一个ConcurrentDictionary集合用以保存下载结果,并且定义了DownloadStringAsync接受一个字符串地址,该方法内首先尝试从缓存中检索内容,如果结果不在缓存中,那么使用异步方法下载字符串,并将其添加到缓存中,返回Task<string>结果。

2.Main方法:

    class Program
    {
        static void Main(string[] args)
        {
            //需要下载的url集合
            string[] urls = new string[] {
                "https://www.cnblogs.com",
                "http://msdn.microsoft.com",
                "http://www.microsoft.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("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("Retrieved {0} characters. Elapsed time was {1} ms.",
                   results.Result.Sum(result => result.Length),
                   stopwatch.ElapsedMilliseconds);
            }).Wait();

            Console.ReadKey();
        }
    }

测试结果:

测试结果

3.结论

​ 此示例计算两次下载多个字符串所需的时间。第二组下载操作应该比第一组少花费时间,因为结果保存在缓存中。该FromResult方法使DownloadStringAsync创建方法任务<TResult>持有这些预先计算的结果对象。

​ 我对“预先”的理解为已经知道的结果,当一个方法需要返回Task对象时,如果有一种情况TResult已经预先知道,让么就可以使用Task.FromResult(TResult)方法返回Task对象。

​ 参考资料:

  1. How to: Create Pre-Computed Tasks

  2. Task.FromResult(TResult) Method


    埼玉镇帖

qiyu

posted @ 2019-09-01 15:15  -猪是念来过倒  阅读(3151)  评论(0编辑  收藏  举报