ASP NET Core 如何执行完全异步操作

How do you perform completely asynchrouns operations in ASP NET Core

你好,我正在尝试为我的一些 API 做一个跟踪日志 endpoints.These 日志是在端点是 called.I 时生成的,希望完成日志的写入以异步方式(尽可能轻量级)不影响我通常逻辑的性能。

我想有一个可注入的组件,当日志是 produced.The 时可以在我的端点的任何地方调用问题是我似乎找不到合适的异步解决方案:

不需要因延误而受阻的重要服务

public interface IImportantInterface
{
    Task DoSomethingUndistrubedAsync(string value);
}

**Wrapper around Redis pub-sub**

 public interface IIOService{
     Task PublishAsync( object obj);
 }

控制器

public class Controller
{
    private IImportantInterface importantService;
    private Publisher publisher;
    [HttpPost]
    public async Task SomeEndpointAsync(){
          this.publisher.Publish([some_log]);
          await this.importantService.DoSomethingUndisturbedAsync([something]);
    }
    public Controller(IImportantInterface importantService)
    {

        this.importantService=importantService;
    }

}

现在真正的 problem.How 我要为我的 Publisher 做最小的足迹吗?我想出了 3 个场景,但其中两个因为超出范围而无法实现:

尝试 1
任务范围为方法的瞬态服务:

public class Publisher{

    private IIOService writeService{get;set;}
    public async Task PublishAsync(object obj){
         Task t1=Task.Run(async()=>await writeService.PublishAsync(obj)); //t1 might not finished when method exits
    }
}

任务 t1 可能不会在方法结束时完成。

尝试 2 瞬态服务中嵌入的任务

public class Publisher{    //publisher might get discarded when calling controller gets out of scope
     private Task t1;
     private IIOService writeService{get;set;}
     public async Task PublishAsync(object obj){        
          t1=Task.Run(async ()=> this.IIOService.writeService(obj));  
     }
}

现在任务不会在方法作用域后被收集,但它可能不会在调用 Controller 方法 class 超出作用域时完成

尝试 3 具有 Tasks 的 ConcurrentQueue 的单例对象已入队。 这不会超出范围,但我什么时候可以清除这些项目?

public class Publisher{
     private ConcurrentQueue<Task> Queue;
     public async Task PublishAsync(object obj){
         this.Queue.Enqueue();
     }
}

P.S 我想将这些日志发布到一个公共 place.From 中,目标是发布到 Redis 数据库使用发布-订阅功能。 我应该写信给 Redis 吗?

Hello i am trying to do a trail log for some of my API endpoints.These logs are generated when the endpoint is called.I would like the writing of the logs to be done in an asynchrouns manner (as lightweight as possible) as to not affect the performance of my usual logic.

我强烈建议您使用经过详尽测试的现有日志记录库,其中有许多具有现代功能,例如语义日志记录和异步兼容的隐式状态。

现代日志库通常采用单例设计,日志保存在内存中(并且日志记录方法是同步的)。然后有一个单独的 "processor" 将这些消息发布到收集器。如果您坚持编写自己的日志框架(为什么?),我建议您采用与所有其他非常成功的日志框架相同的方法。