2011-06-12 47 views
0

我正在每60秒在后台执行一些任务。后台任务是服务器从网站请求下载文件。当请求完成时,主线程/ UI似乎被锁定,我将数据保存到sqlite。NSThread detachNewThreadSelector锁定主线程

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
     [NSThread detachNewThreadSelector:@selector(startTheBackgroundSync) toTarget:self withObject:nil]; 
     [pool release]; 

- (void)startTheBackgroundSync { 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // [self performSelectorInBackground:@selector(moveSynctoBack) withObject:nil]; 
    // [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO]; 

    serverSync = [[[ServerSync alloc]init]autorelease]; 
    while (1==1) { 
     serverSync.delegate = self; 
     [serverSync syncNow:nil]; 
     [NSThread sleepForTimeInterval:120]; 
    } 
    [pool release]; 
    [serverSync release]; 

} 

虽然循环不锁定了主线程,但是当ASIHTtpRequest的数据完成了它锁定了UI进行了第二次。

回答

4

ASIHTTPRequest的完成选择器将始终在主线程上执行。因此你不应该在那里做长时间运行的任务。

,而不启动一个新的线程,你可以安排一个重复的NSTimer:

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(backgroundSync) userInfo:nil repeats:YES]; 

...用下面的操作方法:

-(void) backgroundSync 
{ 
    ServerSync* serverSync = [[[ServerSync alloc]init]autorelease]; 
    serverSync.delegate = self; 
    [serverSync syncNow:nil]; 
} 

确保您使用startAsynchronous - 方法在ServerSync开始请求!

而且我建议实行单,然后用它这样的:

-(void)init { 
    [[ServerSync sharedSync] setDelegate:self]; 
} 

-(void) backgroundSync 
{ 
    [[ServerSync sharedSync] syncNow]; 
} 
+0

是否有可能有ASIHTTPRequest在后台线程或线程它是从所谓的执行? – iosdevnyc 2011-06-12 17:50:17

+0

@harekam_taj是的,你可以在ASIHTTPRequest子类中覆盖'threadForRequest'。请参阅源代码中的注释('ASIHTTPRequest.m')。注意:这只适用于高级用户! – Felix 2011-06-12 18:35:23