我正在尝试并行运行两种方法。第一种方法连接到 ftp 服务器并下载一些数据。因为我想减少它应该每 30 秒运行一次的网络流量。 同时,我希望另一种方法每 10 秒独立于第一种方法运行。
问题是我没有得到并行运行/延迟的方法。
namespace Example
{
class Program
{
static async Task Main(string[] args)
{
await Task.Run(async () =>
{
while (true)
{
await Every10s();
await Every30s();
}
});
}
public static async Task<bool> Every10s()
{
await Task.Delay(10000);
Console.Writeline("10s");
return true;
}
public static async Task<bool> Every30s()
{
await Task.Delay(30000);
Console.Writeline("30s");
return true;
}
}
}
我希望得到以下输出,中间有相应的停顿: 10s 10s 10s 30多岁 10s 10s 10s 30多岁 ...
但是这两种方法相互等待,所以我得到输出 10s 30s 10s 30s 10s 30s 并暂停 40 秒。
感谢任何帮助和提示。
最佳答案
Because I want to reduce the network traffic it should run every 30 s. In parallel I want another method to run independent from the first method every 10 s.
您有两个独立的工作循环,因此您的代码中需要两个循环:
async Task RunEvery10s()
{
while (true)
await Every10s();
}
async Task RunEvery30s()
{
while (true)
await Every30s();
}
await Task.WhenAll(RunEvery10s(), RunEvery30s());
关于c# - 如何异步运行多个方法并延迟并行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56736201/