NSThread,停下来等待2秒钟

时间:2016-08-10 14:04:27

标签: ios objective-c multithreading nsthread

我明确地创建了一个NSThread类的工作线程。

[workerThread cancel]
//how to wait for 2 seconds for the thread to die? I need something like join(2000) in Java

我知道NSThread中没有“join”功能,停止此线程的最佳方法是什么?等待2秒钟让线程死掉? (如在Java Thread join(2000)函数中)

CREATE TABLE [Test].[Persons](
[PersonId] [int] NOT NULL,
[FirstName] [varchar] (50) NOT NULL,
[LastName] [varchar] (50) NOT NULL,
[OtherNames] [varchar] (50) NULL,
[BirthDate] [varchar] (10) NULL
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED ([PersonId] ASC)
)

(请不要谈论GCD,我的问题是关于NSThread,谢谢。)

1 个答案:

答案 0 :(得分:0)

确定调用者线程不是一个好主意,如果可能的话,不确定这样的苹果,但你可以得到一个解决方法......

我认为这样做:

1 /快速而肮脏的NSTimer会检查线程状态每隔x秒,而不是我的一杯茶。

作业完成后,你的doWork选择器中的发布NSNotification并注册它,当它被解雇时,你知道你的线程已经完成......

我确实更喜欢第二种解决方案,是的,GCD rox所以这就是我如何做到这一点:

static NSThread * workerThread;

- (void) startWorkerThread
{
    workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(doWork)  object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workerThreadDidReturn) name:@"workerThreadReturnsNotification" object:nil];
    [workerThread start];

    static NSInteger timeoutSeconds = 5;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // Cancel after timeoutSeconds seconds if not finished yet
        if(![workerThread isCancelled]){
            [workerThread cancel];
        }
    });

}

- (void) doWork
{

    // Do something heavy...
    id result = [NSObject new];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"workerThreadReturnsNotification"
                                                        object:result];
}


- (void) workerThreadDidReturn:(NSNotification *)notif
{
    id result = (id) notify.object;
    // do something with result...

    [workerThread cancel];
}