问题描述
这是参考StackOverflow问题
我有多个异步HTTP请求在同一时间。所有这些使用相同的NSURLConnection委托函数。 (对于每个连接,receiveData对象不同于上面的其他问题)在委托中,我解析receiveDate对象,并对这些解析的字符串做额外的操作)
到目前为止,一切都对我很好,但我不知道我是否需要做任何事情,以确保正确的多线程行为。
- 有可能两个以上的连接同时使用代理吗? (我认为是)
- 如果是,如何解决?
- 是否需要执行其他检查,以确保每个请求都能正确处理?
假设你在单个线程上启动所有的(异步)连接,那么代理消息都将发布在该线程的运行循环。因此,代表只需要能够处理一次处理的一个消息;运行循环将一次关闭一个消息。这意味着虽然委托消息的顺序是未知的,并且下一个消息可能来自任何连接对象,但是不会同时执行您的委托方法。
但是,你实际上是想在多个线程中使用相同的委托对象,而不是仅仅使用API的异步性质,那么你需要处理并发委托方法。
This is with reference to the StackOverflow question Managing multiple asynchronous NSURLConnection connections
I have multiple asynchronous HTTP requests being made at the same time. All these use the same NSURLConnection delegate functions. (The receivedData object is different for each connection as specified in the other question above. In the delegate, I parse the receivedDate object, and do additional operations on those parsed strings)
Everything works fine for me so far, but I'm not sure if I need to do anything to ensure correct "multithreaded" behavior.
- Is it possible that more than two connections will use the delegate at the same time? (I would think yes)
- If yes, how is it resolved? (Does Cocoa do this automatically?)
- Do I need to have additional checks in place to ensure that each request is handled "correctly"?
Assuming you're launching all of the (asynchronous) connections on a single thread, then the delegate messages will all get posted in that thread's run loop. Therefore the delegate only needs to be able to deal with one message being handled at once; the run loop will hand one message off at a time. This means that while the order of the delegate messages is unknown and the next message could come from any connection object, there will be no concurrent execution of your delegate methods.
However, were you actually trying to use the same delegate object across multiple threads, rather than just using the asynchronous nature of the API, then you would need to deal with concurrent delegate methods.
这篇关于Cocoa:使用相同的委托函数检查多个异步NSURLConnections是否需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!