无法访问已处置的对象。使用 SignalR 和定时器管理器

Cannot access a disposed object. with SignalR and Timer Manager

我想让我的函数实时发送数据(每 2 秒一次或一旦数据库发生变化 table),但问题是我下面的代码中存在异常保持应用程序读取。

异常详情为:

'Cannot access a disposed object.
 public class MyHub : Hub
    {
        private readonly IRepository<MyTable, long> _repository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public HCHub(IUnitOfWorkManager unitOfWorkManager,IRepository<MyTable, long> repository)
        {
            _repository = repository;
            _unitOfWorkManager = unitOfWorkManager;

        }

        

        public  void Get(TestDto testDto)
        {
            try {
                using (var unitOfWork = _unitOfWorkManager.Begin())
                {
                    var result=  _repository.GetDbContext().Set<MyTable>()
               .Include(x => x.list)
               .ThenInclude(x => x.list2)
               .ThenInclude(x => x.obj).ToList();




                    new TimerManager(async () =>

                    await Clients.All.SendAsync("listen", result) //<====== in this Line the exception occured
                    
                    
                    );
                }
            }
            catch(Exception ex)
            {
                throw new UserFriendlyException(ex.InnerException.Message.ToString());
            }



        }

TimerManager 代码为

public class TimerManager
    {
        private Timer _timer;
        private AutoResetEvent _autoResetEvent;
        private Action _action;

        public DateTime TimerStarted { get; }

        public TimerManager(Action action)
        {
            _action = action;
            _autoResetEvent = new AutoResetEvent(false);
            _timer = new Timer(Execute, _autoResetEvent, 1000, 2000);
            TimerStarted = DateTime.Now;
        }

        public void Execute(object stateInfo)
        {
            _action();

            if ((DateTime.Now - TimerStarted).Seconds > 60)
            {
                _timer.Dispose();
            }
        }
    }

所以问题出在 Timer ManagermyHub 或我通过 [=21 模拟实时数据的方式=]TimerManager 不接受table ?!

退出集线器方法后,不保证您能够访问 Clients 属性。如果你想做类似的事情,你应该将 IHubContext<THub> 注入你的 Hubs 构造函数并使用它。您可以在 https://docs.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-3.1#get-an-instance-of-ihubcontext

中阅读有关 IHubContext 的更多信息