当我尝试检索结果时,我遇到了阻止任务的问题。
我有以下要同步执行的代码(这就是为什么我要查找结果)
我会忽略每次调用必须进行的原因(传统软件需要通过不同的层进行多次调用)
在启动PostCreateProfile中进行最终调用的任务后,调用似乎崩溃了,我可以看到这个请求永远不会比这更进一步。
if (CreateProfile(demographics).Result) // Task blocks here
{
//dothing
}
private async Task<bool> CreateProfile(Demographics demographics)
{
ProfileService profileService = new ProfileService();
CreateProfileBindingModel createProfileBindingModel = this.CreateProfileModel(demographics);
return await profileService.Create(createProfileBindingModel);
}
public async Task<bool> Create(CreateProfileBindingModel model)
{
HttpResponseMessage response = await profileServiceRequest.PostCreateProfile(rootURL, model);
return response.IsSuccessStatusCode;
}
public Task<HttpResponseMessage> PostCreateProfile(string url, CreateProfileBindingModel model)
{
HttpContent contents = SerialiseModelData(model);
var resultTask = client.PostAsync(url, contents);
return resultTask;
}
如果我要将CreateProfile更改为异步void,请求将到达其目的地:
private async void CreateProfile(AppointmentController controller)
{
ProfileService profileService = new ProfileService();
CreateProfileBindingModel createProfileBindingModel = this.CreateProfileModel(controller);
await profileService.Create(createProfileBindingModel);
}
但是我不能从这里返回我想要使用的bool。 谁能指出我做错了什么?
答案 0 :(得分:1)
You should never call .Result
on a async/await chain
调用CreateProfile(demographics)
的任何代码都需要异步,以便它可以执行
if (await CreateProfile(demographics))
{
//dothing
}
另外,如果你真的可以把.ConfigureAwait(false)
放在逻辑上可能的地方。
if (await CreateProfile(demographics).ConfigureAwait(false)) // depending on what dothing is you may not want it here.
{
//dothing
}
private async Task<bool> CreateProfile(Demographics demographics)
{
ProfileService profileService = new ProfileService();
CreateProfileBindingModel createProfileBindingModel = this.CreateProfileModel(demographics);
return await profileService.Create(createProfileBindingModel).ConfigureAwait(false);
}
public async Task<bool> Create(CreateProfileBindingModel model)
{
HttpResponseMessage response = await profileServiceRequest.PostCreateProfile(rootURL, model).ConfigureAwait(false);
return response.IsSuccessStatusCode;
}
public Task<HttpResponseMessage> PostCreateProfile(string url, CreateProfileBindingModel model)
{
HttpContent contents = SerialiseModelData(model);
var resultTask = client.PostAsync(url, contents);
return resultTask;
}