在asp.netcore web api项目中,有一个名为TimedHostedService的后台服务,通过AddSingleton<>注入,当从控制器访问该服务的成员[ ExecutionCount ]时,该值始终等于0,当设置成员[ ExecutionCount ]时改为static,值就变了,不知道为什么?属性 [ ExecutionCount ] 必须是静态的吗?
\n定时托管服务:
\npublic class TimedHostedService : IHostedService, IDisposable\n{\n private int executionCount = 0;\n private readonly ILogger<TimedHostedService> _logger;\n private Timer _timer;\n\n public int ExecutionCount\n {\n get { return executionCount; }\n set { executionCount = value; }\n }\n\n public TimedHostedService(ILogger<TimedHostedService> logger)\n {\n _logger = logger;\n }\n\n public Task StartAsync(CancellationToken stoppingToken)\n {\n _logger.LogInformation("Timed Hosted Service running.");\n\n _timer = new Timer(DoWork, null, TimeSpan.Zero,\n TimeSpan.FromSeconds(1));\n\n return Task.CompletedTask;\n }\n\n private void DoWork(object state)\n {\n …Run Code Online (Sandbox Code Playgroud)