【问题标题】:Fire and Forget (but not completely)Fire and Forget(但不完全)
【发布时间】:2017-02-19 21:49:27
【问题描述】:

跟进有关 Fire and Forget 的许多问题中提供的解决方案。我的场景是我想按被触发的顺序运行被遗忘的事件。

我的解决方案是基于Simplest way to do a fire and forget method in c# 4.0

这是我的测试代码。正如预期的那样,它从不保证它们将被处理的顺序。

    static void Main(string[] args)
    {
        Test(5);
        Console.WriteLine("5 sent");

        Test(2);
        Console.WriteLine("2 sent");

        Test(1);
        Console.WriteLine("1 sent");

        Test(4);
        Console.WriteLine("4 sent");

        Console.WriteLine("all sent");
        Console.ReadLine();

    }

    private static void Test(int messageNumber)
    {
        Action myMethod = () => {
            Task.Delay(messageNumber * 1000);
            Console.WriteLine(messageNumber);
        };
        Blindly.Run(myMethod);
    }

和我的输出

5 sent
2 sent
1 sent
4 sent
all sent
2
1
5
4

想象一下,您正在使用 Fire and Forget 进行日志记录。所以你不想阻塞调用代码,而是想按发生的顺序写入所有记录的数据。

【问题讨论】:

  • 为什么不将您的操作排队并按您想要的顺序调用它们?
  • 您确实意识到Task.Delay(messageNumber * 1000); 在这种情况下是无用的,因为它没有被等待?下一行之前不会有延迟Console.WriteLine(messageNumber);

标签: c# events logging


【解决方案1】:

我会使用 TPL 数据流的 ActionBlock(有关介绍,请参阅 http://blog.stephencleary.com/2012/09/introduction-to-dataflow-part-2.html

这是一个 NuGet 包,所以看看它是否符合你的框架版本要求。

static void Main(string[] args)
{
    var a = new ActionBlock<int>(async (messageNumber) => 
    {
        await Task.Delay(messageNumber * 1000);
        Console.WriteLine(messageNumber);
    });

    a.Post(5);
    Console.WriteLine("5 sent");

    a.Post(2);
    Console.WriteLine("2 sent");

    a.Post(1);
    Console.WriteLine("1 sent");

    a.Post(4);
    Console.WriteLine("4 sent");

    Console.WriteLine("all sent");
    Console.ReadLine();
}

它将按照发布到ActionBlock的顺序以即发即弃的方式进行处理。

输出:

5 sent
2 sent
1 sent
4 sent
all sent
5
2
1
4

【讨论】:

    【解决方案2】:

    我会做以下事情:

    • 为所有记录的事件保留时间戳
    • 不要立即将事件写入日志(因为您是异步运行它,希望您已经不那么担心了);而是保留一个记录消息的队列(一个集合,不一定是 FIFO)
    • 每 X 毫秒,如果您已将日志消息排队,请对所有早于 Y 毫秒的消息进行排序和记录(X 和 Y 将取决于您的要求/设置)
    • 在应用程序退出时尝试刷新日志(确保您正在这样做,即使它是异常)

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 2013-01-13
      • 2021-10-12
      • 1970-01-01
      • 2023-02-25
      • 2013-11-08
      • 2020-03-05
      • 2020-03-21
      相关资源
      最近更新 更多