Search code examples
c#wpfasynchronousasync-awaitgetasync

Do something periodically while waiting for result of an GetAsync


I want to start an GetAsync or PostAsync and then in a loop do something and check for results.

req1 = client.GetAsync(url_1); // a time consuming request

do
{
    //do something here
    var req2= await client.GetAsync(url_2);
    var result2 = await req2.Content.ReadAsStringAsync();
    
} while (!IsResultReady(req1)); // check if url_1 job is done and stop the loop

var result1 = await req1.Content.ReadAsStringAsync();

Solution

  • this example should give you what you need

    async Task Main()
    {
        var mainTask = MyLongRunningTask();
        // mainTask is already started without await
        do
        {
            await DoSomethingElse();
        } while (!mainTask.IsCompleted);
    }
    
    public async Task MyLongRunningTask()
    {
        Console.WriteLine("Long Running Task Started");
        
        await Task.Delay(3000); // simulating client.GetAsync(url_1)
        
        Console.WriteLine("Long Running Task Finished");
    }
    
    async Task DoSomethingElse()
    {
        Console.WriteLine("doing some other tasks");
        await Task.Delay(1000);
    }
    

    output:

    Long Running Task Started
    doing some other tasks
    doing some other tasks
    doing some other tasks
    Long Running Task Finished