Create Pre Computed Task Using Task FromResult
Task.FromResult
method is useful when you perform an asynchronous operation that returns a Task<TResult>
object, and the result of that Task<TResult>
object is already computed.
The FromResult
method returns a finished Task<TResult>
object that holds the provided value as its Result property.
Samples
Convert a simple synchronous method to asynchronous method
Greeting is a simple method which returns a string
private static string Greeting() {
return "Hello World";
}
public static void Main()
{
var message = Greeting();
Console.WriteLine(message);
}
You can use Task.FromResult
to convert into asynchronous method
private static Task<string> GreetingAsync() {
return Task.FromResult("Hello World");
}
public static async Task Main()
{
var message = await GreetingAsync();
Console.WriteLine(message);
}
Read from Cache if present or download
In the following example DownloadAsync
method checks the cache for given address and uses FromResult
method to produce a Task<TResult>
object that holds the content at that address. Otherwise, DownloadStringAsync
downloads the file from the web and adds the result to the cache.
private static readonly ConcurrentDictionary<string, string> cachedDownloads = new();
private static readonly HttpClient httpClient = new();
public static async Task Main()
{
string[] urls = new[]
{
"https://docs.microsoft.com/aspnet/core",
"https://docs.microsoft.com/dotnet",
"https://docs.microsoft.com/dotnet/azure",
"https://docs.microsoft.com/dotnet/machine-learning",
"https://docs.microsoft.com/xamarin",
};
IEnumerable<Task<string>> downloads1 = urls.Select(DownloadAsync);
await Task.WhenAll(downloads1);
IEnumerable<Task<string>> downloads2 = urls.Select(DownloadAsync);
await Task.WhenAll(downloads2);
}
public static Task<string> DownloadAsync(string address)
{
if(cachedDownloads.TryGetValue(address, out string content)){
Console.WriteLine($"Reading {address} data from cache");
return Task.FromResult(content);
}
return Task.Run(async () => {
var content = await httpClient.GetStringAsync(address);
cachedDownloads.TryAdd(address, content);
Console.WriteLine($"Reading {address} data from web");
return content;
});
}