0

我想开始一个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();
4

1 回答 1

4

这个例子应该给你你所需要的

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
于 2021-07-03T11:45:26.423 回答