2

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;
}
6
  • 11
    The async keyword makes the Task instance transparent to the method and automatically wraps the return value for you, in the same way that the yield statement rewrites a method to turn it into an iterator. Commented Oct 16, 2015 at 8:05
  • 3
    In this case, async isn't involved at all. It's await that instructs the compiler to asynchronously await for a task to finish, then return its result. The result from await Task.FromResult(item) is item. In fact, you could have written return item as your method doesn't do anything asynchronously Commented Oct 16, 2015 at 8:07
  • 1
    Also note that async simply tells the compiler to do await magic. 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 write return httpClient.GetStringAsync(..); and remove the async keyword completely. Commented Oct 16, 2015 at 8:12
  • 1
    Simply speaking, await equals return someTask; return someTask.Result;. Compiler makes the magic that code resume from the first return. Commented Oct 16, 2015 at 8:13
  • 2
    Please define 'doesn't work'. Have you looked at the error message? It's pretty descriptive. I'll bet it reads Cannot convert Task<WorkItem> to Task<Task<WorkItem>> or similar. Commented Oct 16, 2015 at 8:17

1 Answer 1

1

The line item = await Task.FromResult(item) is incorrect, it should actually just read:

return Task.FromResult(item);

As the method is marked as async, you return the task, and then whoever is calling CreateWorkItem() would do so using await, so the caller should look like:

WorkItem item = await CreateWorkItem(myWorkItem);

Or:

Task<WorkItem> itemTask = CreateWorkItem(myWorkItem);
item = await itemTask;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.