Skip to content

介绍下dispatch_group_enter/dispatch_group_leave和dispatch_group_async各自的应用场景以及使用的时候需要注意哪些问题 #80

Open
@tbfungeek

Description

@tbfungeek

dispatch_group_enter/dispatch_group_leavedispatch_group_async二者是等效的,但是使用场景有些许区别:
dispatch_group_enter/dispatch_group_leave:一般用于操作是异步的情况。

dispatch_group_enter(group);
[self sendHttpRequestWithCompletion:^(id response) {
    //操作
    dispatch_group_leave(group);
}];

dispatch_group_async一般用于操作为同步的操作:

dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{    
    writeFile();
});

dispatch_group_enter/dispatch_group_leave在使用的时候需要注意,要成对使用。
如果dispatch_group_leave先于dispatch_group_enter调用,或者dispatch_group_leave调用次数多于dispatch_group_enter就会造成崩溃。

如果dispatch_group_leave调用次数少于dispatch_group_enter 就会导致dispatch_group_notify中的任务无法执行或者dispatch_group_wait收不到信号而卡住线程。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions