-1

我的代码需要在单独的 NSThread 中运行所有网络例程。我有一个库,我通过一个回调例程进行通信:

my thread code
    library
        my callback (networking)
    library
my thread code

我的回调例程必须将一些数据发布到 HTTP 服务器(NSURLConnection),等待答案(启动 NSRunLoop?),然后返回到库。
然后库处理数据。在库返回到我的线程后,我可以向处理绘图和用户输入的主线程发布通知。

是否有任何示例代码涵盖如何在 NSThread 中使用 NSURLConnection?

4

5 回答 5

1

Kelvin's link is dead, here's a bit of code that does what you are asking for (meant to be run in a method called by [NSThread detachNewThreadSelector:toTarget:WithObject:]). Note that the connection basically starts working as soo as you enter the run loop, and that "terminateRunLoop" is meant to be a BOOL set to NO on start and set to YES when the connection finishes loading or has an error.

Why would you want to do this instead of a blocking synchronous request? One reason is that you may want to be able to cancel a long-running connection properly, even if you do not have a lot of them. Also I have seen the UI get hung up a bit if you start having a number of async requests going on in the main run loop.

NSURLConnection *connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain];
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
while(!terminateRunLoop) 
{
    if ( ![[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode 
                                   beforeDate:[NSDate distantFuture]]) 
        {  break; }

        [pool drain];
    }
    [pool release];
}
于 2009-03-27T01:26:18.590 回答
1

如果你需要阻塞直到你完成工作并且你已经在一个单独的线程上,你可以使用+[NSURLConnection sendSynchronousRequest:returningResponse:error:]. 不过这有点生硬,所以如果您需要更多控制权,您必须切换到NSURLRequest在当前NSRunLoop. 在这种情况下,一种方法可能是在完成时让您的委托标记,并允许运行循环处理事件,直到设置标记或超过超时。

于 2008-10-05T09:20:37.197 回答
0

NSURLConnection 可以通过其异步委托方法在后台线程(例如 NSThread 或 NSOperation)中同步使用。但是,它确实需要了解 NSRunLoop 的工作原理。

这里有一篇带有示例代码和解释的博客文章: http ://stackq.com/blog/?p=56

示例代码下载了一个图像,但我使用这个概念对 REST API 进行复杂的 POST 调用。

-开尔文

于 2008-12-09T23:01:09.260 回答
0

您使用线程的任何特殊原因?除非您打开很多连接,否则主线程上的 NSRunLoop 应该足够好。如果您需要做阻塞工作作为响应,那么请创建您的线程。

于 2008-12-10T00:02:51.413 回答
0

要回答您的小问题“启动 NSRunLoop?”:

我不确定我是否理解,但听起来你是在说你上面的伪代码都是在辅助线程上执行的(即,不是主事件处理线程)。如果是这种情况,创建 NSRunLoop 可能没有任何意义,因为在等待 HTTP 服务器响应时,您无法做任何有用的工作。只是让线程阻塞。

于 2008-10-02T00:48:10.250 回答