简体   繁体   English

System.ObjectDisposedException异常

[英]System.ObjectDisposedException

----- Cannot access a disposed context instance. ----- 无法访问已处置的上下文实例。 A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application.此错误的一个常见原因是处理从依赖项注入解析的上下文实例,然后尝试在应用程序的其他地方使用相同的上下文实例。 This may occur if you are calling---这可能会发生,如果你打电话---

Hi can any one help me to resolve this problem嗨,谁能帮我解决这个问题

public class RealTimeMessage : ControllerBase
{
    private IHubContext<MessageHub, IMessageHubClient> messageHub;
    private readonly JobbyContext _Context;
    private  TimerManager _timer;
    public RealTimeMessage(IHubContext<MessageHub, IMessageHubClient> _messageHub,JobbyContext C,TimerManager T)
    {
        messageHub = _messageHub;
        _Context = C;
        _timer = T;
    }

    [HttpGet]
    [Route("SendMessage")]
    public  async Task<IActionResult> SendRealTimeMessage()
    {

        if (!_timer.IsTimerStarted)
         await _timer.PrepareTimer( async()=>
            {
                var m = await _Context.message.ToListAsync(x=> x.IsRead==false);// **=> Error here**
                if (m.Count>0)
                {
                    await messageHub.Clients.All.SendMessageToUser(m);
                }
                

            });
        
        return Ok(new { Message = "Request Completed" });
        
    }
}

public class TimerManager
{
    private Timer? _timer;
    private AutoResetEvent? _autoResetEvent;
    private Func<Task>? _action;
    public DateTime TimerStarted { get; set; }
    public bool IsTimerStarted { get; set; }

    public   async Task PrepareTimer(Func<Task> action)
    {
        _action =  action;
        _autoResetEvent = new AutoResetEvent(false);
        _timer = new  Timer(Execute, _autoResetEvent, 1000, 3000);
        TimerStarted = DateTime.Now;
        IsTimerStarted = true;
       
    }

    public async void Execute(object? stateInfo)
    {
        await _action();

        if ((DateTime.Now - TimerStarted).TotalSeconds > 10000)
        {
            IsTimerStarted = false;
                _timer.Dispose();

            
        }
    }
}

I would recommend a significant change in how this works.我会建议对其工作方式进行重大更改。

  • When a user opens the site for the first time, it fetches all their unread messages当用户第一次打开网站时,它会获取他们所有未读的消息
  • Every time a message is sent, it is always broadcast via SignalR to the recipient每次发送消息时,它总是通过 SignalR 广播给接收者

If the recipient is connected, they will receive the message immediately via SignalR.如果收件人已连接,他们将立即通过 SignalR 收到消息。 If they are not connected, they will receive it when they open the site.如果他们没有连接,他们将在打开网站时收到它。 This will drastically simplify the implementation, and will reduce load on the database.这将大大简化实施,并减少数据库的负载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM