【发布时间】:2014-03-04 06:29:06
【问题描述】:
我正在编写一个可以同时执行多项任务的应用程序。一项特定任务是每 200 毫秒一次完成一项工作。为此,我使用了两种相互调用的方法。第一种方法只调用第二种方法,第二种方法使用 dispatch_after() 延迟调用第一种方法。
经过几次迭代(300-400 次),dispatch_after 中的块在 200 毫秒后不执行。 执行块需要大约 5-10 秒。请让我知道行为的原因(延迟)。我也尝试了 NSThread (sleepForTimeInterval:) 我也面临同样的问题。我被卡住了。请帮帮我。
代码如下。
Screen.h
#import <Foundation/Foundation.h>
@interface Screen : NSObject
-(void) firstMethod;
-(void) secondMethod;
@end
Screen.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
【问题讨论】:
-
通常发生这种情况的原因是,无论你做什么都需要很长时间,所以下一次运行循环旋转的时间已经过去了。
-
@GradyPlayer,为了检查行为,我简化了代码并发布在上面。在上面的代码中,我只是增加一个变量并打印它。我认为这不应该花费太多时间。如果我的理解是错误的,请您对此进行更多说明。
-
@SenthilGanesh,简化代码是否具有相同的行为?因为看起来你第二次分别调用了 fistMethod 或 secondMethod 而不是在你的 200ms 循环中。
-
@Cy-4AH,我在上面的代码中遇到了问题。对不起,我不明白你的意思。能详细点吗?
-
该问题与“运行循环”无关。其他事情正在发生。
标签: objective-c multithreading macos objective-c-blocks nsthread