Advertisement
ivandrofly

C# - Task.FromResult

Mar 15th, 2014
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.89 KB | None | 0 0
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7.  
  8. // Demonstrates how to use Task<TResult>.FromResult to create a task  
  9. // that holds a pre-computed result.
  10. class CachedDownloads
  11. {
  12.    // Holds the results of download operations.
  13.    static ConcurrentDictionary<string, string> cachedDownloads =
  14.       new ConcurrentDictionary<string, string>();
  15.  
  16.    // Asynchronously downloads the requested resource as a string.
  17.    public static Task<string> DownloadStringAsync(string address)
  18.    {
  19.       // First try to retrieve the content from cache.
  20.       string content;
  21.       if (cachedDownloads.TryGetValue(address, out content))
  22.       {
  23.          return Task.FromResult<string>(content);
  24.       }
  25.  
  26.       // If the result was not in the cache, download the  
  27.       // string and add it to the cache.
  28.       return Task.Run(async () =>
  29.       {
  30.          content = await new WebClient().DownloadStringTaskAsync(address);
  31.          cachedDownloads.TryAdd(address, content);
  32.          return content;
  33.       });
  34.    }
  35.  
  36.    static void Main(string[] args)
  37.    {
  38.       // The URLs to download.
  39.       string[] urls = new string[]
  40.       {
  41.          "http://msdn.microsoft.com",
  42.          "http://www.contoso.com",
  43.          "http://www.microsoft.com"
  44.       };
  45.  
  46.       // Used to time download operations.
  47.       Stopwatch stopwatch = new Stopwatch();
  48.  
  49.       // Compute the time required to download the URLs.
  50.       stopwatch.Start();
  51.       var downloads = from url in urls
  52.                       select DownloadStringAsync(url);
  53.       Task.WhenAll(downloads).ContinueWith(results =>
  54.       {
  55.          stopwatch.Stop();
  56.  
  57.          // Print the number of characters download and the elapsed time.
  58.          Console.WriteLine("Retrieved {0} characters. Elapsed time was {1} ms.",
  59.             results.Result.Sum(result => result.Length),
  60.             stopwatch.ElapsedMilliseconds);
  61.       })
  62.       .Wait();
  63.  
  64.       // Perform the same operation a second time. The time required
  65.       // should be shorter because the results are held in the cache.
  66.       stopwatch.Restart();
  67.       downloads = from url in urls
  68.                   select DownloadStringAsync(url);
  69.       Task.WhenAll(downloads).ContinueWith(results =>
  70.       {
  71.          stopwatch.Stop();
  72.  
  73.          // Print the number of characters download and the elapsed time.
  74.          Console.WriteLine("Retrieved {0} characters. Elapsed time was {1} ms.",
  75.             results.Result.Sum(result => result.Length),
  76.             stopwatch.ElapsedMilliseconds);
  77.       })
  78.       .Wait();
  79.    }
  80. }
  81.  
  82. /* Sample output:
  83. Retrieved 27798 characters. Elapsed time was 1045 ms.
  84. Retrieved 27798 characters. Elapsed time was 0 ms.
  85. */
  86. http://msdn.microsoft.com/en-us/library/hh228607.aspx
  87. http://stackoverflow.com/questions/19568280/what-is-the-use-for-task-fromresulttresult-in-c-sharp
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement