Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an async method:

public async Task<bool> ValidateRequestAsync(string userName, string password)
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync(url);
        string stringResponse = await response.Content.ReadAsStringAsync();

        return bool.Parse(stringResponse);
    }
}

I call this method like this:

bool isValid = await ValidateRequestAsync("user1", "pass1");

Can i call the same method from an synchronous method, without using await keyword?

Ex:

public bool ValidateRequest(string userName, string password)
{
    return ValidateRequestAsync(userName, password).Result;
}

I think this will cause a deadlock.

EDIT

Calling the method like above makes the call never end. (The method doesn't reaches the end anymore)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
498 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you call an async method from a single threaded execution context, such as a UI thread, and wait for the result synchronously, there is a high probability for deadlock. In your example, that probability is 100%

Think about it. What happens when you call

ValidateRequestAsync(userName, password).Result

You call the method ValidateRequestAsync. In there you call ReadAsStringAsync. The result is that a task will be returned to the UI thread, with a continuation scheduled to continue executing on the UI thread when it becomes available. But of course, it will never become available, because it is waiting (blocked) for the task to finish. But the task can't finish, because it is waiting for the UI thread to become available. Deadlock.

There are ways to prevent this deadlock, but they are all a Bad Idea. Just for completeness sake, the following might work:

Task.Run(async () => await ValidateRequestAsync(userName, password)).Result;

This is a bad idea, because you still block your UI thread waiting and doing nothing useful.

So what is the solution then? Go async all the way. The original caller on the UI thread is probably some event handler, so make sure that is async.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...