Why is this working? Return type is NOT Task.
public async Task<WorkItem> CreateWorkItem(WorkItem workItem)
{
WorkItem item = new WorkItem();
workItem.Description = "something";
item = await Task.FromResult(item);
return item;
}
Why is this not working? Return type is Task.
public async Task<WorkItem> CreateWorkItem(WorkItem workItem)
{
WorkItem item = new WorkItem();
workItem.Description = "something";
Task<WorkItem> result = await Task.FromResult(item);
return result;
}
asynckeyword makes theTaskinstance transparent to the method and automatically wraps the return value for you, in the same way that theyieldstatement rewrites a method to turn it into an iterator.asyncisn't involved at all. It'sawaitthat instructs the compiler to asynchronously await for a task to finish, then return its result. The result fromawait Task.FromResult(item)isitem. In fact, you could have writtenreturn itemas your method doesn't do anything asynchronouslyasyncsimply tells the compiler to doawaitmagic. If only the last call in your method is asynchronous, there's no need to await for the result, you can simply return the task.Assuming your method did something really asynchronous like an HTTP call, you could writereturn httpClient.GetStringAsync(..);and remove theasynckeyword completely.awaitequalsreturn someTask; return someTask.Result;. Compiler makes the magic that code resume from the first return.Cannot convert Task<WorkItem> to Task<Task<WorkItem>>or similar.