美文网首页
线程保活

线程保活

作者: 晨阳Xia | 来源:发表于2021-03-17 17:10 被阅读0次

ViewController.h


#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface XSYThreadSaveActive : NSObject

/// 执行任务
/// @param task 任务
- (void)executeTask:(void(^)(void))task;

/// 取消任务
- (void)cancelTask;

@end

NS_ASSUME_NONNULL_END



ViewController.m


#import "XSYThreadSaveActive.h"

@interface XSYThread : NSThread

@end

@implementation XSYThread

- (void)dealloc {
    NSLog(@"I am dead %s",__func__);
}

@end

@interface XSYThreadSaveActive ()

@property (strong, nonatomic) XSYThread *thread;
@property (assign, nonatomic, getter = isStop) BOOL stop;

@end

@implementation XSYThreadSaveActive

- (instancetype)init {
    self = [super init];
    if (self) {
        self.stop = NO;
        __weak typeof(self)weakSelf = self;
        self.thread = [[XSYThread alloc] initWithBlock:^{
            [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
            while (weakSelf && !weakSelf.isStop) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        }];
        [self.thread start];
    }
    return self;
}

#pragma mark - Public method

// 执行任务
- (void)executeTask:(void (^)(void))task {
    if (!self.thread || !task) {
        return;;
    }
    
    // waitUntilDone这个参数到底是什么意思?
    [self performSelector:@selector(__executeTask:) onThread:self.thread withObject:task waitUntilDone:NO];
    
}

// 取消任务
- (void)cancelTask {
    if (!self.thread) {
        return;
    }
    
    [self performSelector:@selector(stop) onThread:self.thread withObject:nil waitUntilDone:YES];
}


#pragma mark - Private method

// 取消任务
- (void)stop {
    self.stop = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.thread = nil;
}

- (void)__executeTask:(void (^)(void))task {
    task();
}

@end


相关文章

  • RunLoop -- 在实际开发中的应用

    1、控制线程生命周期<线程保活> 线程保活 2、解决NSTimer在滑动时失效的问题 当scrollView滑动的...

  • iOS底层原理——浅谈RunLoop

    RunLoop应用:线程保活 线程保活、控制销毁 iOS-浅谈RunLoop8iOS底层原理总结 - RunLoo...

  • iOS NSThread 保活线程代码封装

    iOS NSThread 保活线程代码封装

  • iOS Runloop的理解与使用

    Runloop的概念 Runloop的存在主要就是为了线程保活,线程保活是为了线程能够及时的处理事件,不会在其执行...

  • 线程保活

    在实际开发中,我们可能很多操作需要放在子线程中操作,可能会重复的创建线程。这个时候我们就需要创建一个线程并不让其销...

  • 线程保活

    线程保活是在多线程中进行耗时操作常用的功能: 常规开启方式,会出现内存泄漏 通过 [runloop run]直接...

  • 线程保活

    #import "ViewController.h" #import "WZJthread.h" @interfa...

  • 线程保活

    线程保活 当子线程中的任务执行完毕后,线程就被立刻销毁了。如果程序中,需要经常在子线程中执行任务,频繁的创建和销毁...

  • 线程保活

    ViewController.h ViewController.m

  • iOS底层探索 --- RunLoop(实战)

    日常开发中我们常用的RunLoop场景有: 线程保活 Timer相关 APP卡顿检测 线程保活首先我们应该达成的共...

网友评论

      本文标题:线程保活

      本文链接:https://www.haomeiwen.com/subject/zjyecltx.html