我需要等待整个任务完成然后返回一个值。我的代码给了我一个错误的"不是所有的代码路径返回一个值"。你能告诉我怎么修这个吗?我真的很困惑的任务。
public async override Task<TagInfoReply> GetInfo(TagInfoRequest request, ServerCallContext context)
{
var tagInfo = JsonSerializer.Deserialize<TagInfo>(request.TagInfo);
var parameter = JsonSerializer.Deserialize<ParameterGetWhiteListWithEntryInfo>(request.DetectedTag);
var task = Task.Run(() =>
{
return filters.FilterTags(tagInfo);
});
await task.ContinueWith(
async antecedent =>
{
if (antecedent.Result)
{
var reply = await pcs.GetTagInfo(parameter, tagInfo, TagFilterTime);
return new TagInfoReply
{
FetchedTagInfo = reply
};
}
else
{
return new TagInfoReply
{
FetchedTagInfo = string.Empty
};
}
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
如果我输入
return new TagInfoReply
{
FetchedTagInfo = string.Empty
};
在任务的最后和外部。ContinueWith,错误消失了,但问题是,当它运行时,它不会等待任务完成。它直接到最后一个返回。
目前,您的return
代码仅从您传递给ContinueWith
的匿名方法返回,并且它们将返回给ContinueWith
内的调用代码。你实际上没有从GetInfo
返回任何东西。
ContinueWith
的结果作为其结果提供给您,因此您应该能够像这样重写代码:
public async override Task<TagInfoReply> GetInfo(TagInfoRequest request, ServerCallContext context)
{
var tagInfo = JsonSerializer.Deserialize<TagInfo>(request.TagInfo);
var parameter = JsonSerializer.Deserialize<ParameterGetWhiteListWithEntryInfo>(request.DetectedTag);
var task = Task.Run(() =>
{
return filters.FilterTags(tagInfo);
});
return await task.ContinueWith(
async antecedent =>
{
if (antecedent.Result)
{
var reply = await pcs.GetTagInfo(parameter, tagInfo, TagFilterTime);
return new TagInfoReply
{
FetchedTagInfo = reply
};
}
else
{
return new TagInfoReply
{
FetchedTagInfo = string.Empty
};
}
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
问题的核心是需要返回一个值。一个附带的问题是,你不应该使用ContinueWith
在所有。如果您将ContinueWith
替换为await
,那么您的代码将变得更加清晰:
public async override Task<TagInfoReply> GetInfo(TagInfoRequest request, ServerCallContext context)
{
var tagInfo = JsonSerializer.Deserialize<TagInfo>(request.TagInfo);
var parameter = JsonSerializer.Deserialize<ParameterGetWhiteListWithEntryInfo>(request.DetectedTag);
var result = await Task.Run(() =>
{
var filteredTags = filters.FilterTags(tagInfo);
if (antecedent.Result)
{
var reply = await pcs.GetTagInfo(parameter, tagInfo, TagFilterTime);
return new TagInfoReply
{
FetchedTagInfo = reply
};
}
else
{
return new TagInfoReply
{
FetchedTagInfo = string.Empty
};
}
});
return result;
}
你也可能不需要Task.Run
在那里:
public async override Task<TagInfoReply> GetInfo(TagInfoRequest request, ServerCallContext context)
{
var tagInfo = JsonSerializer.Deserialize<TagInfo>(request.TagInfo);
var parameter = JsonSerializer.Deserialize<ParameterGetWhiteListWithEntryInfo>(request.DetectedTag);
var filteredTags = filters.FilterTags(tagInfo);
if (antecedent.Result)
{
var reply = await pcs.GetTagInfo(parameter, tagInfo, TagFilterTime);
return new TagInfoReply
{
FetchedTagInfo = reply
};
}
else
{
return new TagInfoReply
{
FetchedTagInfo = string.Empty
};
}
}