等待其他线程在 Objective C 中完成
我正在使用 MGTwitterEngine 从 Twitter 获取推文。这使用异步范例在另一个线程中获取推文。它将获取的结果返回到主线程。
因为在获取推文后我还有一些处理待办事项,所以我想引入另一个线程来防止锁定 UI 线程。 我想这样做: UI 线程启动一个新线程 X。线程 X 启动使用 MGTEngine 异步获取推文,并等待完成。当 MGTwitterEngine 返回时,线程 X 处理推文,并通知 UI 线程我们已准备好。
我的问题是:如何设置线程 X 等待 MGTwitterEngine 被读取?
I am using MGTwitterEngine to fetch tweets from twitter. This uses a asynchrounous paradigm to fetch that tweetsin another thread. It returns the fetched results to the main thread.
Because I have some processing todo after the tweets are fetched, I would like to introduce another thread to prevent locking the UI thread.
I would lik to do it this way:
UI thread starts a new thread X. thread X starts the asynchronous fetching of tweets with MGTEngine, and waits for that to finish. When MGTwitterEngine returns, thread X processes the tweets, and notifies the UI thread that we are ready.
My question is: How to set thread X to wait till MGTwitterEngine is reade?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
现在几乎没有借口不使用带有块的多线程。它们比 NSOperations 开发更快,同步更简单,跳转线程(例如抓取 UI 线程)更简单,而且根据我自己的经验,它的性能更好。
在这种情况下,我将创建一个块,生成一个新线程来启动异步获取(可能为每个线程生成一个异步获取 - 使取消更容易)将 2 个同步块放入队列中,该队列将在获取完成后触发处理和 UI 更新。
这是一个很好的评论: http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/
There is very little excuses not to use multithreading with blocks now. They are quicker to develop than NSOperations, synchronisation is simpler, jumping threads (e.g. grabbing the UI thread) is simpler and in my own experience it performance is better.
In this case, I would create a block, spawn a new thread to fire up your async fetch (possibly spawning an async fetch for each one- makes cancelations easier) put 2 sync blocks in the queue that will fire after the fetches are done for the processing and the UI update.
Here is a good tut: http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/
有两种方法可以做到这一点。
使用阻塞网络调用 --- 如果可能。
调用 CFRunLoopRun() --- 等待另一个事件来继续线程中的操作。异步数据获取完成后,在线程 x 中的 X runloops 上下文上调用 CFRunLoopStop()。
There are 2 ways you can do this.
Use blocking netwrok calls --- if posible.
Call CFRunLoopRun() --- to wait for another event to proceed with the operation in the thread. Once a asynchronous data fetching is done call CFRunLoopStop() on X runloops context in thread x.