Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c# - call async method without await #2

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...