fix UI block issues

This commit is contained in:
SoftFever
2026-02-02 18:12:19 +08:00
parent d817a4d5d4
commit 431943408b
7 changed files with 124 additions and 65 deletions

View File

@@ -139,6 +139,7 @@ void NetworkAgent::set_printer_agent(std::shared_ptr<IPrinterAgent> printer_agen
// Local copies to allow safe access after releasing the lock.
// This pattern ensures the objects stay alive (via shared_ptr refcount) even if
// another thread modifies m_printer_agent or m_printer_callbacks after we unlock.
std::shared_ptr<IPrinterAgent> old_printer_agent;
std::shared_ptr<IPrinterAgent> new_printer_agent;
PrinterCallbacks callbacks;
@@ -152,6 +153,8 @@ void NetworkAgent::set_printer_agent(std::shared_ptr<IPrinterAgent> printer_agen
// Disconnect all callbacks from the old agent
apply_printer_callbacks(m_printer_agent, callbacks);
// Capture the old agent before overwriting so we can disconnect it outside the lock
old_printer_agent = m_printer_agent;
// Take ownership of the incoming agent and update the agent ID
m_printer_agent = std::move(printer_agent);
m_printer_agent_id = m_printer_agent->get_agent_info().id;
@@ -164,6 +167,11 @@ void NetworkAgent::set_printer_agent(std::shared_ptr<IPrinterAgent> printer_agen
}
// Lock released here - m_agent_mutex is now free for other threads
// Disconnect the old agent's connections/threads. The cache keeps it alive,
// but we release its network resources while it's not the active agent.
if (old_printer_agent && old_printer_agent != new_printer_agent)
old_printer_agent->disconnect_printer();
// Apply callbacks OUTSIDE the lock to avoid deadlock risk and minimize
// critical section duration. The local shared_ptr copy ensures the agent
// cannot be destroyed while we're using it.