简体   繁体   中英

C# How async-await works with long operations?

I have the following code in my service:

        // add Txt record to DNSimple with verification text
        await CreateDomainRecordAsync(domain, new DomainRecordDto
        {
            //....
        });

        // verify domain on Office365
        await _office365domainService.VerifyDomainAsync(domain);

Where first operation is call endpoint #1 (domain registrator) and add TXT record to domain. Second operation is call endpoint #2 (Office365), which verify whether TXT record exists in domain registrator.

This code does not work, I get an exception on the second operation, that TXT record does not exist.

I created test code:

    public IActionResult LongOperation()
    {
        Thread.Sleep(10 * 1000);
        return Ok();
    }

    public IActionResult Test()
    {
        return Ok();
    }

and call it:

        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri("http://test***.azurewebsites.net/home/");
            await httpClient.GetAsync("LongOperation");
        }

        using (HttpClient httpClientLocal = new HttpClient())
        {
            httpClientLocal.BaseAddress = new Uri("https://localhost:44366/Home");
            await httpClientLocal.GetAsync("Test");
        }

It works as I expect, call first method, wait 10 sec while "LongOperation" is being executed and then call "Test" method.

Why my real code with domains does not wait and how to do it correctly?

You may not even have a problem with async-await.

The first operation executes async and you wait, but this is a DNS config change - it may not be visible office 365 for minutes thanks to multiple DNS caching layers. The wrong assumption here is that:

  • DNS changes are visible immediately
  • This is an async/await problem.

Generally for stuff like DNS you may want to retry every like 15 seconds and give up after some time, or employ a workflow that handles longer outtimes. This is not async/await related - it is the same like with emails where the server may delay delivery. It is part of the protocol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM