0

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();
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Hamid Z
  • 180
  • 1
  • 14
  • You seem to be just ignoring result2. I think the code might have lost some meaning. If i follow what you intend then you could put the req2 stuff in s separate thread starter tyat and just await the req1. Stop the req2 thread using a cancellation token after the await, when req1 returns it's result. – Andy Jul 03 '21 at 11:56

1 Answers1

4

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
AliReza Sabouri
  • 4,355
  • 2
  • 25
  • 37