【问题标题】:How to know when a task in other thread finished?如何知道其他线程中的任务何时完成?
【发布时间】:2013-11-08 00:37:34
【问题描述】:

我想在其他线程(不是主线程)解析一些数据

for (NSString* theKey in [rssSourcesData allKeys])
 {
      NSURL *url = [NSURL URLWithString:theKey];
      NSURLRequest *initialRequest = [NSURLRequest requestWithURL:url];
     AFGDataXMLRequestOperation *oper = [AFGDataXMLRequestOperation
XMLDocumentRequestOperationWithRequest:initialRequest 
success:^(NSURLRequest *request, NSHTTPURLResponse *response, GDataXMLDocument *XMLDocument) {
            [self parseDataInBackground:XMLDocument forKey:theKey];

        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, GDataXMLDocument *XMLDocument) {

            NSLog(@"failure handler: %@",theKey);

        }];

        [oper start];
}

finshied 解析完其他线程中的所有数据后,我想返回主线程。该怎么做?

【问题讨论】:

  • 您可以在代码中使用块来强制应用返回主线程。或者,您可以添加一个侦听器并在 parseDataInBackground 完成时发布 NSNotification,以便侦听器可以执行之后的代码。此链接可能有助于理解:stackoverflow.com/questions/10492138/…

标签: ios iphone multithreading asynchronous concurrency


【解决方案1】:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // do your work here

    dispatch_async(dispatch_get_main_queue(), ^{
        // on the main thread
    }) ;
}) ;

gcd 更有效。

【讨论】:

  • 您的意思是:dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // do your work here dispatch_async(dispatch_get_main_queue(), ^{ // on the main thread }) ; }) ;
  • 是的,说实话我对你的代码了解不多,但我认为我列出的代码会对你有所帮助。您可以修改代码以适应条件。
  • 这里是关于GCD的链接Concurrency Programming Guide
【解决方案2】:
 [self performSelectorOnMainThread:@selector(parseFinished:) withObject:dataObject waitUntilDone:[NSThread isMainThread]];

一旦你结束解析数据,使用此方法返回主线程并通知数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-06
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    相关资源
    最近更新 更多