feat: save event_loop handle to avoid ghost session

This commit is contained in:
caoqianming 2026-03-06 09:38:14 +08:00
parent b197607d5f
commit 76b6e17927
1 changed files with 18 additions and 2 deletions

View File

@ -98,6 +98,7 @@ pub struct ConnectionStatus {
pub poll_points: Arc<Vec<PollPointInfo>>, // 正在轮询的点集合 pub poll_points: Arc<Vec<PollPointInfo>>, // 正在轮询的点集合
poll_handle: Option<JoinHandle<()>>, // 统一的轮询任务句柄 poll_handle: Option<JoinHandle<()>>, // 统一的轮询任务句柄
heartbeat_handle: Option<JoinHandle<()>>, // 心跳任务句柄 heartbeat_handle: Option<JoinHandle<()>>, // 心跳任务句柄
event_loop_handle: Option<JoinHandle<opcua::types::StatusCode>>, // event_loop 任务句柄
} }
#[derive(Clone)] #[derive(Clone)]
@ -577,8 +578,13 @@ impl ConnectionManager {
} }
}; };
let _ = event_loop.spawn(); let event_loop_handle = event_loop.spawn();
session.wait_for_connection().await;
if !session.wait_for_connection().await {
let error = "Session connection failed".to_string();
self.fail_connect(source_id, &error).await;
return Err(error);
}
let mut status = self.status.write().await; let mut status = self.status.write().await;
status.insert( status.insert(
@ -595,6 +601,7 @@ impl ConnectionManager {
poll_points: Arc::new(Vec::new()), poll_points: Arc::new(Vec::new()),
poll_handle: None, poll_handle: None,
heartbeat_handle: None, heartbeat_handle: None,
event_loop_handle: Some(event_loop_handle),
}, },
); );
drop(status); // 显式释放锁,在调用 start_unified_poll_task 之前 drop(status); // 显式释放锁,在调用 start_unified_poll_task 之前
@ -625,6 +632,7 @@ impl ConnectionManager {
poll_points: Arc::new(Vec::new()), poll_points: Arc::new(Vec::new()),
poll_handle: None, poll_handle: None,
heartbeat_handle: None, heartbeat_handle: None,
event_loop_handle: None,
}, },
); );
} }
@ -661,6 +669,10 @@ impl ConnectionManager {
if let Some(handle) = conn_status.heartbeat_handle.take() { if let Some(handle) = conn_status.heartbeat_handle.take() {
handle.abort(); handle.abort();
} }
// 停止 event_loop 任务
if let Some(handle) = conn_status.event_loop_handle.take() {
handle.abort();
}
} }
} }
@ -693,6 +705,10 @@ impl ConnectionManager {
if let Some(handle) = conn_status.heartbeat_handle.take() { if let Some(handle) = conn_status.heartbeat_handle.take() {
handle.abort(); handle.abort();
} }
// 停止 event_loop 任务
if let Some(handle) = conn_status.event_loop_handle.take() {
handle.abort();
}
} }
} }