代码之家  ›  专栏  ›  技术社区  ›  Patroclus

更新UI元素而不分派到主队列

  •  0
  • Patroclus  · 技术社区  · 8 年前

    dispatch_block_t 传递给 另一个功能 将在 功能 完成异步任务。但问题是我不知道

    我想在 主螺纹 ,因此我想使用

    dispatch_async(dispatch_get_main_queue(), ^{...})
    

    更新我的用户界面。但我担心这会导致 死锁 如果这种情况发生

    dispatch_queue_t queue = dispatch_queue_create("my.label", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        dispatch_async(queue, ^{
            // outer block is waiting for this inner block to complete,
            // inner block won't start before outer block finishes
            // => deadlock
        });
    
        // this will never be reached
    }); 
    

    有办法防止 死锁 ? 就像不使用 dispatch queue weak reference self 为了更新用户界面?

    1 回复  |  直到 8 年前
        1
  •  1
  •   markvasiv    8 年前

    尝试使用NSLogs运行您的示例,您将注意到不会发生死锁。这是因为使用 dispatch_async dispatch_sync ).

    dispatch_queue_t queue = dispatch_queue_create("my.label", DISPATCH_QUEUE_SERIAL);
    
    dispatch_async(queue, ^{
        NSLog(@"1");
        dispatch_async(queue, ^{
            NSLog(@"2");
        });
        NSLog(@"3");
    });
    

    将生成以下日志:

    Testtt[32153:2250572] 1
    Testtt[32153:2250572] 3
    Testtt[32153:2250572] 2
    

    dispatch_async(dispatch_get_main_queue(), ^{...}) 这里是确保使用者在主线程上获得结果的常用技术(即使用者不关心线程)。

    不过,你为什么用 dispatch_block_t