objective-c - dispatch_after() 的奇怪行为

标签 objective-c multithreading macos objective-c-blocks nsthread

我正在编写一个将同时执行多项任务的应用程序。一项特定任务是每 200 毫秒执行一次。为此,我使用了两种相互调用的方法。第一个方法只调用第二个,第二个方法使用 dispatch_after() 延迟调用第一个。

经过几次迭代(300-400 次) dispatch_after 中的 block 在 200 毫秒后未执行。 执行 block 需要大约 5-10 秒。请让我知道行为(延迟)的原因。我也试过 NSThread (sleepForTimeInterval:),我也面临着同样的问题。我被卡住了。请帮助我。

代码如下。

屏幕.h

#import <Foundation/Foundation.h>

@interface Screen : NSObject

-(void) firstMethod;
-(void) secondMethod;
@end

屏幕.m

#import "Screen.h"

@implementation Screen

int i=0;
dispatch_queue_t another_queue;
dispatch_time_t pop_time;

-(Screen*) init {
    self = [super init];
    if (self) {
        another_queue = dispatch_queue_create("com.test.timer.2", NULL);
    }
    return self;
}

-(void) firstMethod {
    i++;
    NSLog(@"i value : %d",i);
    [self secondMethod];
}

-(void) secondMethod {
    pop_time = dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC);
    dispatch_after(pop_time, another_queue, ^(void){
        [self firstMethod];
    });
}

@end

AppDelegate.h

#import <Cocoa/Cocoa.h>
#import "Screen.h"

@interface AppDelegate : NSObject <NSApplicationDelegate>

@property (assign) IBOutlet NSWindow *window;

@end

AppDelegate.m

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    Screen* screen = [[Screen alloc] init];
    dispatch_queue_t first_queue = dispatch_queue_create("com.test.timer", NULL);
    dispatch_block_t blk =^(void) {
        [screen firstMethod];
    };
    dispatch_async(first_queue, blk);
}

@end

最佳答案

发生这种情况时,您的应用程序是否在前台?如果没有,您可能只是看到 App Nap 开始运行。它所做的其中一件事是限制后台应用程序中的计时器。

关于objective-c - dispatch_after() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164571/

相关文章:

objective-c - 未找到方法定义...使用 Xcode 自动 stub ?

c++ - 来自主线程的信号未到达第二线程 Qt 5 中的插槽

c++ - 海湾合作委员会ld : symbol(s) not found for architecture i386

python - MacOS 上的 Tkinter Python 3 缩放问题

objective-c - 苹果事件 : Send port for process has no send right

iphone - 在 Objective C 中使用计时器调用函数时如何传递参数

ios - UIToolbar 和 CGRectMake

asp.net - HttpModule 是否在工作线程之间共享?

ios - 我们可以在 QuickBlox 中向离线用户发送系统消息吗?

android - Android UI 线程的工作方式与 Swing UI 线程类似吗?