簡體   English   中英

System.ObjectDisposedException異常

[英]System.ObjectDisposedException

----- 無法訪問已處置的上下文實例。 此錯誤的一個常見原因是處理從依賴項注入解析的上下文實例,然后嘗試在應用程序的其他地方使用相同的上下文實例。 這可能會發生,如果你打電話---

嗨,誰能幫我解決這個問題

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

            
        }
    }
}

我會建議對其工作方式進行重大更改。

  • 當用戶第一次打開網站時,它會獲取他們所有未讀的消息
  • 每次發送消息時,它總是通過 SignalR 廣播給接收者

如果收件人已連接,他們將立即通過 SignalR 收到消息。 如果他們沒有連接,他們將在打開網站時收到它。 這將大大簡化實施,並減少數據庫的負載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM