【发布时间】:2017-03-02 17:56:02
【问题描述】:
我是 swift 新手,在任何主要线程工作方面都没有过多的经验,所以我正在尝试提高我的技能,希望得到一些帮助或指导。这是一个我似乎无法弄清楚的概念。
我有一个类通过输入和输出流进行通信,应用程序通过输出流发送,并从输入流中读取结果。现在我已经创建了通过回调发送异步的方法,但我希望能够同步发送,并在更高级别处理线程。 目前我的沟通方式是这样的:
typealias CommunicationCallback = ((CommunicationResult) -> Void)
func sendAsync(send message: String, closure: @escaping CommunicationCallback) {
DispatchQueue.global().async { [weak self] in
guard let strongSelf = self else {
return
}
let messagePair = MessagePair(SendReceiveResult(sent: message, received: nil),
closure)
strongSelf.writeQueue.enqueue(messagePair)
strongSelf.writeFromQueue() //Calls the CommunicationCallback closure after it has read result
}
}
func sendSyncronized(send message: String) -> CommunicationResult {
???
}
有没有像上面那样包装异步的通用方法? 万一我认为这是完全错误的,在某些情况下我想简单地打电话
let result = sendSyncronized("foo")
而不是做
send("foo", closure: { result in
switch result {
case .a:
foo()
base .b:
bar()
}
})
每次,因为在某些情况下,我需要在等待上一个结果的同时进行许多顺序写入。 欢迎任何帮助!
【问题讨论】:
标签: ios swift multithreading asynchronous closures