Task. FromResult Application Scenario example: task. fromresult
Task. FromResult is used to create a completed Task with a returned value.
Scenario 1: Synchronous implementation of an asynchronous Interface Method
For example, an interface contains an Asynchronous Method.
interface IMyInterface
{
Task<int> DoSthAsync();
}
Now, you need to implement the method DoSthAsync in synchronous mode, but return asynchronous results. This is where Task. FromResult is used.
public class MyClass : IMyInterface
{
public Task<int> DoSthAsync()
{
int result = 1;
return Task.FromResult(result);
}
}
In the preceding steps, the DoSthAsync method of the implementation class MyClass is implemented in synchronous mode, but the returned result is a Task <int>. Using Task. FromResult can return a asynchronous result with a value.
Scenario 2: Get the value from the cache and implement it in synchronous or asynchronous mode
Assume that you need to obtain the value from the cache based on the key. If the cache corresponding to each key does not exist, you need to obtain the cache asynchronously. If yes, you can directly obtain the value from the cache.
Write an asynchronous method to obtain the cache.
private async Task<string> GetValueAsync(int key)
{
string result = await SomeAsyncMethod();
cache.TrySetValye(key, result);
return result;
}
Now you need to write a method to get the value in the cache, either asynchronously or synchronously (obtained from the local cache ).
public Task<string> GetValueFromCache(int key)
{
string result = string.Empty;
if(cache.TryGetValue(key, out result))
{
return Task.FromResult(result);
}
return GetValueAsync(key);
}
Above, obtaining values from the local cache is synchronous, but the type returned by the method is asynchronous Task. , Asynchronous results are returned through Task. FromResult (result.
In addition, if Task. FromResult is used without the return value, Task. FromResult (0) or Task. FromResult is used.(Null ).