简体   繁体   English

c#中的异步触发和遗忘

[英]Asynchronous fire and forget in c#

Currently I am about to develop logging for ac# application into a SQL server table.目前,我正准备将 ac# 应用程序的日志记录开发到 SQL 服务器表中。

I have a designated class called Logger that has a static method writeToLog() .我有一个名为Logger的指定类,它有一个静态方法writeToLog()

I just want to call that static function without block the calling thread.我只想在不阻塞调用线程的情况下调用该静态函数。

How is this possible in C# clean and fast?这在 C# 中怎么可能干净又快速?

The functions don't return anything they are just fire and forget.这些函数不会返回任何东西,它们只是被遗忘。

Thanks for you advice谢谢你的建议

There is the chance that the serveral available logging libraries out there have spent some thoughts about performance.有几个可用的日志库可能已经对性能进行了一些思考。

If you still need to develop a light weight solution yourself I think of two ways.如果您仍然需要自己开发轻量级解决方案,我会想到两种方法。

1.) Create a Task that runs the logging function, without awaiting them 1.) 创建一个运行日志功能的Task ,无需等待它们

2.) The Log-Method saves the Log-Information in a queue that is written to the SQL-database with a background thread. 2.) 日志方法将日志信息保存在一个队列中,该队列通过后台线程写入 SQL 数据库。

I would recommend the second way, because the logging itself can be done in a synchronous function call without the Task creation overhead.我会推荐第二种方式,因为日志本身可以在同步函数调用中完成,而不会产生任务创建开销。

Another argument for this approach is that it is possible to gurantee the order of log messages.这种方法的另一个论点是可以保证日志消息的顺序。 By using a Task for each single message the order of execution is not defined.通过为每条消息使用一个任务,执行的顺序是没有定义的。

And a last argument: It might be more performant to write blocks of messages to the SQL table.最后一个论点:将消息块写入 SQL 表可能会更高效。 By using the queue you will be able write messages in a bulk operation.通过使用队列,您将能够在批量操作中写入消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM