【问题标题】:Objective-C, best way to handle NSTask that isn't finishedObjective-C,处理未完成的 NSTask 的最佳方法
【发布时间】:2019-11-16 01:29:26
【问题描述】:

我有一个异步的dispatch queue,它在后台从大文件中读取数据。在此过程中,它会做一些其他事情,包括一些 NSTask 操作。我面临的问题是我用这些操作的结果填充了一些变量,并且在这些变量准备好(不是 NULL)时后台队列已经移动。

我的代码如下所示:

dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(backgroundQueue, ^{

    // reading large files
    ...
    NSTaskClass *operation = [[NSTaskClass alloc] init];
    NSString *result = [operation doTask:filePath];

    NSLog(@"result: %@" result); // returns NULL since task isn't done yet.
    ...
    // continue large file operations
});

这将是处理此问题的最佳方法吗?我考虑创建一个callback,但我无法弄清楚,我不确定这是否是正确的方法。感谢您提供有关最佳做法的任何建议,谢谢。

【问题讨论】:

  • 不是后台,是另一个进程。你真的需要在另一个进程中读取大文件吗?只有在运行某些服务器时才有意义。

标签: objective-c macos dispatch nstask


【解决方案1】:

只是给你一个想法,希望能解决你的问题。

  • 使用dispatch_sempahore 处理NSTaskClass 中的操作
  • doTask 方法创建一个处理程序,使用- (void)doTask:(NSString *)filePath handler:(void(^)(NSString *result))handler 而不是- (NSString *)doTask:(NSString *)filePath

然后,您的代码应该如下所示:

    dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(backgroundQueue, ^{

        // reading large files
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);

        ...
        NSTaskClass *operation = [[NSTaskClass alloc] init];
        [operation doTask:filePath handler:^(NSString * _Nonnull result) {
            // Get your result here
            result = [NSString stringWithString:result];

            ...

            dispatch_semaphore_signal(sema);


        }];

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

        NSLog(@"result: %@" result); // Here should be fine (not NULL)
        ...
        // continue large file operations
    });

【讨论】:

  • 嗨,我试过你的建议,但似乎一旦我打电话给我的NSTaskClass,它就再也不会回来了。我不确定为什么。如果您需要更多信息,请告诉我,因为我想让这项工作正常进行,谢谢。
  • @JoeHabadas 那么,NSTaskClass 的对象中有任何后台作业吗?如果可能的话,请你给我更多关于你的代码的细节
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多