相关疑难解决方法(0)

Swift线程处理:什么时候使用DispatchQueue.main.async?

我相信我知道调用它时调度队列在做什么,但是我不确定何时应该确切地使用它,以及当我使用它时它的优点是什么。

如果我的理解是正确的,DispatchQueue.main.async { // code }将调度包含在闭包中的代码以异步方式在主调度队列上运行。主队列具有最高优先级,通常保留用于更新UI以最大化App响应能力。

我感到困惑的地方是:更新调度队列闭包中的UI元素与只在闭包外的同一位置编写代码有什么区别?在加载了方法的视图主体中执行代码而不是将其发送到调度队列是否更快?如果没有,为什么?

代码示例:

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        updateUI()
    }

}
Run Code Online (Sandbox Code Playgroud)

与:

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        DispatchQueue.main.async {
            updateUI()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个会更快更新UI?

user-interface multithreading swift

4
推荐指数
1
解决办法
1156
查看次数

"阻塞"主线程(dispatch_get_main_queue())和(或不)定期运行currentRunLoop - 有什么区别?

我有以下代码:

- (void)test_with_running_runLoop {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSTimeInterval checkEveryInterval = 0.05;

    NSLog(@"Is main queue? : %d", dispatch_get_current_queue() == dispatch_get_main_queue());

    dispatch_async(dispatch_get_main_queue(), ^{
        sleep(1);
        NSLog(@"I will reach here, because currentRunLoop is run");
        dispatch_semaphore_signal(semaphore);
    });

    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:checkEveryInterval]];

    NSLog(@"I will see this, after dispatch_semaphore_signal is called");
}

- (void)test_without_running_runLoop {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSLog(@"Is main queue? : %d", dispatch_get_current_queue() == dispatch_get_main_queue());

    dispatch_async(dispatch_get_main_queue(), ^{
        sleep(1);
        NSLog(@"I will not reach here, because currentRunLoop is not run");
        dispatch_semaphore_signal(semaphore);
    }); …
Run Code Online (Sandbox Code Playgroud)

queue semaphore objective-c nsrunloop ios

3
推荐指数
1
解决办法
3825
查看次数