0

I have a function that calls to an external user profile WebAPI via HttpClient asynchronously. Base on the returned profile, the function passes some property values as parameters to a repository to get parameterized data. The problem is the function proceeds to get the data from the repository even before the async method returns any response. I would have used a blocking sync method, but HttpClient only provides GetAsync and ReadAsStringnAsync methods. What should I do? Thanks.

    private async Task <IQueryable<WorkItem>> GetSingleProfile(string networkName) {
      UserProfile thisProfile = await HttpClientWrapper.Get < UserProfile > (
        System.Configuration.ConfigurationManager.AppSettings["userWebApiEndpoint"], "User/networkname/" + networkName);

      IQueryable <WorkItem> userWorkItems = Enumerable.Empty<WorkItem>().AsQueryable();

      if (thisProfile != null) {
        userWorkItems = _workRepository.getWorkItem(thisProfile.userId);
      }
      return userWorkItems;
    }
user266909
  • 1,841
  • 3
  • 32
  • 58

1 Answers1

0

The problem is the function proceeds to get the data from the repository even before the async method returns any response.

Then await the task returned from GetSingleProfile. I assume you're currently calling it something like this:

...
GetSingleProfile(...);
repository.GetWhatever(...);
...

and it should be:

...
await GetSingleProfile(...);
repository.GetWhatever(...);
...

Note that GetSingleProfile should be named GetSingleProfileAsync, which is an indication to the users that the caller probably should await it.

I would have used a blocking sync method, but HttpClient only provides GetAsync and ReadAsStringnAsync methods.

If you want it to be synchronous for some reason, then just use WebClient instead.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810