您如何在ASP NET Core中执行完全异步的操作

问题描述 投票:0回答:1

你好,我正在尝试为我的某些API端点创建跟踪日志。这些日志是在调用端点时生成的。我希望以异步方式(尽可能轻巧)编写日志),以免影响我通常的逻辑性能。

[我本以为有一个可注入的组件,并且在生成日志时可以在端点的任何地方调用它。问题是我似乎找不到合适的异步解决方案:

不需要延迟的重要服务

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

**Wrapper around Redis pub-sub**

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

Controller

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;
    }

}

现在是真正的问题。我如何为我的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方法类超出作用域时可能无法完成

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

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

P.S我想在公共位置发布这些日志。从该位置开始,目标是使用pub-sub功能发布到Redis数据库。我应该只写Redis吗?

asp.net-core redis task-parallel-library publish-subscribe
1个回答
0
投票

您好,我正在尝试为我的一些API端点创建跟踪日志。这些日志是在调用端点时生成的。我希望以异步方式(尽可能轻巧)编写日志不影响我通常的逻辑性能。

© www.soinside.com 2019 - 2024. All rights reserved.