Result of a async task is blocking

前端 未结 1 1282
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 16:58

I have an issue with a task blocking when I try to retrieve it\'s result.

I have the following piece of code I want executed synchronously (which is why I\'m looking for

相关标签:
1条回答
  • 2021-01-28 17:30

    You should never call .Result on a async/await chain.

    Whatever code that calls CreateProfile(demographics) needs to be async too so it can do

    if (await CreateProfile(demographics))
    {
        //dothing
    }
    

    Also, if you can you really should put .ConfigureAwait(false) wherever it is logically possible.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题