Abdulaziz Burghal
Abdulaziz Burghal

Reputation: 866

Cannot access a disposed object. with SignalR and Timer Manager

I wanna make my function send data as a real time (every 2 seconds or once there is change in the database table ) but the problem is there is Exception keep appread in my below code.

The exception details are:

'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());
            }



        }

and TimerManager Code is

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

So the problem is in Timer Manager or in myHub or the way that I'm simulate the realtime data by TimerManager is not acceptable ?!

Upvotes: 0

Views: 901

Answers (1)

Brennan
Brennan

Reputation: 1931

Once you exit the hub method you aren't guaranteed to be able to access the Clients property. If you want to do something like that, you should inject an IHubContext<THub> into your Hubs constructor and use that instead. You can read more about IHubContext in https://learn.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-3.1#get-an-instance-of-ihubcontext

Upvotes: 1

Related Questions