Abdur Rahim
Abdur Rahim

Reputation: 4021

async await losing response in c#

The following code is working fine: its sample code downloaded from GitHub and set with my image and API keys.

 static void Main(string[] args)
    {
        Foo().GetAwaiter().GetResult();
        Console.ReadKey();
    }

    static async Task Foo()
    {
        var antiCaptcha = new AntiCaptcha("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        // Get current balance
        var balance = await antiCaptcha.GetBalance();

        string base64captcha = "Here is a base64 string of a captcha";

        // Solve image captcha
        var image = antiCaptcha.SolveImage(base64captcha);
        image.Wait();

        var res = image.Result;
}

My application is different: There I have also implemented the same.

 public async Task<AntiCaptchaResult> AntiCaptchaSolution(string ApplicationId, string captchaBase64, string Success)
    {
        var antiCaptcha = new AntiCaptcha("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        // Solve image captcha
        var image = antiCaptcha.SolveImage(captchaBase64);
        image.Wait();

        return image.Result;
    }

When I don't debug it does not respond anything.

And When I am debugging, the debugger disappears after the anticaptcha.SolveImage line and never comes and nothing happens afterward.

**I am calling this method from another method: **

 public string GetFirstCaptcha(string Success="False")
    {
captchasrc = "";
var res = AntiCaptchaSolution(applicationid, captchasrc, Success).GetAwaiter().GetResult();
    }

Upvotes: 1

Views: 519

Answers (1)

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30175

I suggest that you use await everywhere you are doing .Wait() now. It is non trivial to understand the complexity of async/await and how it does work, but one thing is clear: better not to combine async with blocking .Wait(). It can result in a deadlock.

There are many explanations around the web, e.g. here.

Alternatively if you don't have async/await in your whole stack, you can just remove async from your AntiCaptchaSolution method, and do an ordinary blocking call with .Result/.Wait(), but then it will of course not be asynchronous.

Upvotes: 3

Related Questions