[英]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 收到消息。 如果他們沒有連接,他們將在打開網站時收到它。 這將大大簡化實施,並減少數據庫的負載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.