【发布时间】:2022-01-24 08:31:05
【问题描述】:
我在我的 ASP.NET MVC 项目中遇到了HostedService / 背景类的一些问题。
我需要的是一个计时器,它每 X 秒处理一次某些功能,当这些功能达到目标时,停止并重复该过程。
我已经在 StartUp 文件中实现了如下服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddTransient<INetLogger, Log4NetLogger>();
services.AddSingleton<IConfigurationSetting, ConfigurationSetting>();
services.AddSingleton<BackgroundService, StrategyLoops>();
services.AddSingleton<IStrategyManager, StrategyManager>();
services.AddSingleton<IUnitOfWork, UnitOfWork>();
}
我已经创建了包含继承的类,并且我有 UnitOfWork 的构建器。
在这个类中,我得到了应该包含程序逻辑的ExectuteAsync函数。
public class StrategyLoops : BackgroundService
{
private readonly IUnitOfWork Uow;
public StrategyLoops(IUnitOfWork uow)
{
Uow = uow;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Do logic stuff
await Task.Delay(2000, stoppingToken);
}
}
}
现在,我的问题是什么?
当我启动程序时,什么也没有发生。我放了一些调试断点,但是编译器不通过代码,逻辑不启动。
此逻辑调用服务器的 API 并且正在运行 while 循环,如果我没有计时器,服务器会因过载请求而将我踢出。
项目一开始有点不同,我有一个“策略管理器”类,实现了不同的逻辑
services.AddSingleton<IStrategyManager, StrategyManager>();
为了探测逻辑,我是直接从HomeController调用方法,但现在我不知道如何开始......
请注意,我是 OOP 的菜鸟 ...
StrategyManager:
public class StrategyManager : IStrategyManager
{
public bool IsDivisible(decimal x, decimal n){}
public decimal SpotTradeWallet(){}
private const int indexValore = 0;
private const int indexQuantity = 1;
private const string SELL = "sell";
private const string BUY = "buy";
public void Strategia1(IUnitOfWork uow, String symbol, decimal startValue, decimal
startQuantity){}
public void Strategia2(IUnitOfWork uow, string POBsymbol, string SOsymbol, string
HTsymbol, string SBsymbol, string Ssymbol){}
}
另一个问题,我的知识问题,是我不明白我是否也可以在StrategyManager 类中实现后台服务,所以我可以更容易地从视图中调用它。
非常感谢任何愿意回答我的人
【问题讨论】:
-
您是否将
services.AddHostedService<StrategyLoops>();添加到 ConfigureServices 方法中? -
当然,正如您在第一个代码分区中看到的那样。添加为 Singleton services.AddSingleton
(); -
或者你的意思是别的什么?在这种情况下,你是什么意思?
标签: c# visual-studio model-view-controller asp.net-core-hosted-services