0

In my application, I am trying to update the user profile which calls the Rest API. API has one sync method UpdateProfile where execution getting stuck.

this line of code is ending the execution

command.UserProfile.LookupItems = GetLookupItemsByUserId(existingUser.Id).Result;

When i changed this line of code to

command.UserProfile.LookupItems = Task.Run(async () => await GetLookupItemsByUserId(existingUser.Id)).Result;

It started working without any issue.Can anybody explain to me what is going on behind the scene?

nilsK
  • 4,323
  • 2
  • 26
  • 40

2 Answers2

2

The first version is blocking the current thread, when the task complete the blocked thread cannot catch it.

YourType Signature() {
    var neverUsedValue = task.Result;
}

The second one is yielding the current "thread" until the task is returned.

YourType Signature() {
    var value = Task.Run(await => async MethodThatWillComplete()).Result
}

What you should do is propagate the async to the method:

async Task<YourType> SignatureAsync() {
    command.UserProfile.LookupItems = await GetLookupItemsByUserId(existingUser.Id);
}

In this way you will avoid handling the AggregateException.

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
  • Since this method is used in so many places. I have not changed the method return type. instead used this code "command.UserProfile.LookupItems = Task.Run(async () => await GetLookupItemsByUserId(existingUser.Id)).Result;" which works for me. – Deependra Kushwah Jul 25 '19 at 12:10
1

There is very well written article on this here:Don't block async In a few words, blocking on async code is bad because it may be blocking the thread which is supposed to run the async code and thus generete a deadlock.

Bruno Belmondo
  • 2,299
  • 8
  • 18