为什么这样有效?返回类型不是任务。
public async Task<WorkItem> CreateWorkItem(WorkItem workItem)
{
WorkItem item = new WorkItem();
workItem.Description = "something";
item = await Task.FromResult(item);
return item;
}
为什么这不起作用?返回类型是任务。
public async Task<WorkItem> CreateWorkItem(WorkItem workItem)
{
WorkItem item = new WorkItem();
workItem.Description = "something";
Task<WorkItem> result = await Task.FromResult(item);
return result;
}
答案 0 :(得分:1)
订单项=等待Task.FromResult(item)不正确,它实际上应该只是读取:
return Task.FromResult(item);
由于该方法被标记为异步,您返回任务,然后调用CreateWorkItem()的任何人都将使用await执行此操作,因此调用者应该如下所示:
WorkItem item = await CreateWorkItem(myWorkItem);
或者:
Task<WorkItem> itemTask = CreateWorkItem(myWorkItem);
item = await itemTask;