在等待 GetAsync 的结果时定期做一些事情

Do something periodically while waiting for result of an GetAsync

我想开始一个 GetAsyncPostAsync,然后循环执行一些操作并检查结果。

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();

这个例子应该能满足您的需求

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);
}

输出:

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