建立已預先計算的工作
在本文中,您將了解如何使用 Task.FromResult 方法擷取保留在快取中之非同步下載作業的結果。 FromResult 方法會傳回已完成的 Task<TResult> 物件,該物件中會保存提供的值做為其 Result 屬性。 當您執行會傳回 Task<TResult> 物件的非同步作業,而且該 Task<TResult> 物件的結果已計算時,這個方法很有用。
範例
下列範例將會從網路下載字串。 它會定義 DownloadStringAsync
方法。 這個方法會以非同步方式從網路下載字串。 這個範例也會使用 ConcurrentDictionary<TKey,TValue> 物件快取先前作業的結果。 如果這個快取中保存了輸入位址,DownloadStringAsync
就會使用 FromResult 方法產生保存該位址內容的 Task<TResult> 物件。 否則,DownloadStringAsync
會從網路下載檔案,並將結果加入至快取。
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
public static class DownloadCache
{
private static readonly ConcurrentDictionary<string, string> s_cachedDownloads = new();
private static readonly HttpClient s_httpClient = new();
public static Task<string> DownloadStringAsync(string address)
{
if (s_cachedDownloads.TryGetValue(address, out string? content))
{
return Task.FromResult(content);
}
return Task.Run(async () =>
{
content = await s_httpClient.GetStringAsync(address);
s_cachedDownloads.TryAdd(address, content);
return content;
});
}
public static async Task Main()
{
string[] urls = new[]
{
"https://zcusa.951200.xyz/aspnet/core",
"https://zcusa.951200.xyz/dotnet",
"https://zcusa.951200.xyz/dotnet/architecture/dapr-for-net-developers",
"https://zcusa.951200.xyz/dotnet/azure",
"https://zcusa.951200.xyz/dotnet/desktop/wpf",
"https://zcusa.951200.xyz/dotnet/devops/create-dotnet-github-action",
"https://zcusa.951200.xyz/dotnet/machine-learning",
"https://zcusa.951200.xyz/xamarin",
"https://dotnet.microsoft.com/",
"https://www.microsoft.com"
};
Stopwatch stopwatch = Stopwatch.StartNew();
IEnumerable<Task<string>> downloads = urls.Select(DownloadStringAsync);
static void StopAndLogElapsedTime(
int attemptNumber, Stopwatch stopwatch, Task<string[]> downloadTasks)
{
stopwatch.Stop();
int charCount = downloadTasks.Result.Sum(result => result.Length);
long elapsedMs = stopwatch.ElapsedMilliseconds;
Console.WriteLine(
$"Attempt number: {attemptNumber}\n" +
$"Retrieved characters: {charCount:#,0}\n" +
$"Elapsed retrieval time: {elapsedMs:#,0} milliseconds.\n");
}
await Task.WhenAll(downloads).ContinueWith(
downloadTasks => StopAndLogElapsedTime(1, stopwatch, downloadTasks));
// Perform the same operation a second time. The time required
// should be shorter because the results are held in the cache.
stopwatch.Restart();
downloads = urls.Select(DownloadStringAsync);
await Task.WhenAll(downloads).ContinueWith(
downloadTasks => StopAndLogElapsedTime(2, stopwatch, downloadTasks));
}
// Sample output:
// Attempt number: 1
// Retrieved characters: 754,585
// Elapsed retrieval time: 2,857 milliseconds.
// Attempt number: 2
// Retrieved characters: 754,585
// Elapsed retrieval time: 1 milliseconds.
}
Imports System.Collections.Concurrent
Imports System.Net.Http
Module Snippets
Class DownloadCache
Private Shared ReadOnly s_cachedDownloads As ConcurrentDictionary(Of String, String) =
New ConcurrentDictionary(Of String, String)()
Private Shared ReadOnly s_httpClient As HttpClient = New HttpClient()
Public Function DownloadStringAsync(address As String) As Task(Of String)
Dim content As String = Nothing
If s_cachedDownloads.TryGetValue(address, content) Then
Return Task.FromResult(Of String)(content)
End If
Return Task.Run(
Async Function()
content = Await s_httpClient.GetStringAsync(address)
s_cachedDownloads.TryAdd(address, content)
Return content
End Function)
End Function
End Class
Public Sub StopAndLogElapsedTime(
attemptNumber As Integer,
stopwatch As Stopwatch,
downloadTasks As Task(Of String()))
stopwatch.Stop()
Dim charCount As Integer = downloadTasks.Result.Sum(Function(result) result.Length)
Dim elapsedMs As Long = stopwatch.ElapsedMilliseconds
Console.WriteLine(
$"Attempt number: {attemptNumber}{vbCrLf}" &
$"Retrieved characters: {charCount:#,0}{vbCrLf}" &
$"Elapsed retrieval time: {elapsedMs:#,0} milliseconds.{vbCrLf}")
End Sub
Sub Main()
Dim cache As DownloadCache = New DownloadCache()
Dim urls As String() = {
"https://zcusa.951200.xyz/aspnet/core",
"https://zcusa.951200.xyz/dotnet",
"https://zcusa.951200.xyz/dotnet/architecture/dapr-for-net-developers",
"https://zcusa.951200.xyz/dotnet/azure",
"https://zcusa.951200.xyz/dotnet/desktop/wpf",
"https://zcusa.951200.xyz/dotnet/devops/create-dotnet-github-action",
"https://zcusa.951200.xyz/dotnet/machine-learning",
"https://zcusa.951200.xyz/xamarin",
"https://dotnet.microsoft.com/",
"https://www.microsoft.com"
}
Dim stopwatch As Stopwatch = Stopwatch.StartNew()
Dim downloads As IEnumerable(Of Task(Of String)) =
urls.Select(AddressOf cache.DownloadStringAsync)
Task.WhenAll(downloads).ContinueWith(
Sub(downloadTasks)
StopAndLogElapsedTime(1, stopwatch, downloadTasks)
End Sub).Wait()
stopwatch.Restart()
downloads = urls.Select(AddressOf cache.DownloadStringAsync)
Task.WhenAll(downloads).ContinueWith(
Sub(downloadTasks)
StopAndLogElapsedTime(2, stopwatch, downloadTasks)
End Sub).Wait()
End Sub
' Sample output:
' Attempt number 1
' Retrieved characters: 754,585
' Elapsed retrieval time: 2,857 milliseconds.
'
' Attempt number 2
' Retrieved characters: 754,585
' Elapsed retrieval time: 1 milliseconds.
End Module
在上述範例中,第一次下載每個 url 時,其值會儲存在快取中。 FromResult 方法會讓 DownloadStringAsync
方法建立保存這些預先計算結果的 Task<TResult> 物件。 後續下載字串的呼叫會傳回快取的值,而且速度更快。