c# - 如何异步运行多个方法并延迟并行

标签 c# asynchronous methods parallel-processing task

我正在尝试并行运行两种方法。第一种方法连接到 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/

相关文章:

c++ - 在 C++ 中,在类定义之内还是之外定义方法体更传统?

C# 日期时间 SqlNullValueException : Data is Null

c# - 如何将计数添加到 Winform 中的按钮单击

c - memset 用 'a' 填充文件

c# - 什么时候应该使用 Task.Run()?

java - 无法解析在公共(public)方法中启动的对象?

scala - 为什么有些集合类除了类方法之外还有一个 "empty"实例方法?

c# - lucene 2.9.2.2 一个很奇怪的问题,不能搜索关键字 "a",其他的可以

c# - 无法将大量数据写入流

c# - 在C#中使用async/await和httpclient进行多线程