Skip to content

Commit 18ca443

Browse files
committed
refactor: replace nslock with actor for thread-safe state management
- introduce resumestate actor to handle concurrent access control - remove manual lock handling in favor of actor-based synchronization - maintain same timeout and continuation behavior with cleaner implementation
1 parent f1ce658 commit 18ca443

File tree

1 file changed

+28
-21
lines changed

1 file changed

+28
-21
lines changed

Sources/TeliQKit/NCSocket/NCSocketRequest.swift

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -28,33 +28,40 @@ public class NCSocketRequest {
2828
self.socket = socket
2929
}
3030

31+
private actor ResumeState {
32+
private var hasResumed = false
33+
34+
init() {}
35+
36+
func checkAndSetResumed() -> Bool {
37+
if hasResumed {
38+
return false
39+
}
40+
hasResumed = true
41+
return true
42+
}
43+
}
44+
3145
private func sendRequest<T: Decodable, P: Encodable>(_ sender: (action: String, param: P, echo: String)) async throws -> T {
32-
let lock = NSLock()
33-
var hasResumed = false
34-
3546
return try await withCheckedThrowingContinuation { continuation in
47+
let state = ResumeState()
48+
3649
socket.send(sender) { (result: Result<T, Error>) in
37-
lock.lock()
38-
defer { lock.unlock() }
39-
40-
guard !hasResumed else { return }
41-
hasResumed = true
42-
43-
switch result {
44-
case .success(let response):
45-
continuation.resume(returning: response)
46-
case .failure(let error):
47-
continuation.resume(throwing: error)
50+
Task {
51+
guard await state.checkAndSetResumed() else { return }
52+
53+
switch result {
54+
case .success(let response):
55+
continuation.resume(returning: response)
56+
case .failure(let error):
57+
continuation.resume(throwing: error)
58+
}
4859
}
4960
}
50-
61+
5162
Task {
5263
try? await Task.sleep(nanoseconds: 5_000_000_000) // 5秒超时
53-
lock.lock()
54-
defer { lock.unlock() }
55-
56-
guard !hasResumed else { return }
57-
hasResumed = true
64+
guard await state.checkAndSetResumed() else { return }
5865
continuation.resume(throwing: NCSocketError.timeout)
5966
}
6067
}
@@ -357,7 +364,7 @@ public class NCSocketRequest {
357364
let sender = NCSocketSender.getGroupFileUrl(groupId: groupId, fileId: fileId)
358365
return try await sendRequest(sender)
359366
}
360-
367+
361368
// MARK: - NapCat 协议
362369

363370
/// 获取好友消息历史

0 commit comments

Comments
 (0)