我正在尝试在objective C中实现并发。我有一个需要以同步方式运行的操作的问题。这里的问题是我使用了在完成后执行块的函数。

我想连接到蓝牙设备以运行一些操作并连接到下一个设备。

for (Beacon * beacon in beacons) {
    [beacon setDelegate:self];
    [beacon connectToBeacon];
}

但是连接是异步的。连接成功后,信标将调用委托方法(在本例中为同一类)didConnectSuccess

我需要等待“beaconDidConnect”中的所有操作并断开连接才能完成,然后再连接到下一个设备。

我目前使用调度队列和调度信号量的组合,我的信号量是一个变量

dispatch_queue_t myCustomQueue;
myCustomQueue = dispatch_queue_create("com.example.MyCustomQueue", NULL);

for (Beacon * beacon in beacons) {
    [beacon setDelegate:self];
    dispatch_async(myCustomQueue, ^{
        dispatch_semaphore_wait(semaphoreBluetooth, DISPATCH_TIME_FOREVER);
        [beacon connectToBeacon];

    });
}

与结合

- (void)beaconDidDisconnect:(Beacon *)beacon
{
    dispatch_semaphore_signal(semaphoreBluetooth);
}

如果没有dispatch_async,则通过阻止回调(beaconDidConnect),等待将导致死锁。
我想在for循环中而不是在dispatch块中使用dispatch_semaphore_wait,但是等待导致回调再次等待,从而导致死锁。

这样看来可行,但我发现它有点难看。

我的另一个问题是,在我的beaconDidConnect方法中,我需要链接asynchronous调用,并且每次等待前一个都要终止。

所有这些调用都有一个终止块,在调用完成时执行。我可以在越来越深的块中编写指令,但我想避免这种情况。

我需要等价的javascript“ promise ”概念。

目前,我的调度队列和调度信号量有些问题,但有时由于未知原因有时会出现死锁。

例如:

- (void)beaconConnectionDidSucceeded:(Beacon *)beacon
{
    dispatch_semaphore_t semaphoreEditing = dispatch_semaphore_create(1);
    dispatch_queue_t editingQueue = dispatch_queue_create("com.example.MyCustomQueue.Editing", NULL);

    // First writing procedure
    dispatch_async(editingQueue, ^{
        dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
        [beacon writeSomeCaracteristic:caracteristic withValue:value withCompletion:^(void) {
            dispatch_semaphore_signal(semaphoreEditing);
        }];
    });

    // A unknow number of writing sequences
    dispatch_async(editingQueue, ^{
        dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
        [beacon writeSomeCaracteristic:caracteristic withValue:value withCompletion:^(void) {
            dispatch_semaphore_signal(semaphoreEditing);
        }];
    });
    //
    // ...
    //
    dispatch_async(editingQueue, ^{
        dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
        [beacon writeSomeCaracteristic:caracteristic withValue:value withCompletion:^(void) {
            dispatch_semaphore_signal(semaphoreEditing);
        }];
    });

    // Terminate the edition
    dispatch_async(editingQueue, ^{
        dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
        [beacon disconnectBeacon];
        dispatch_semaphore_signal(semaphoreEditing);
    });
}

我想编写清晰的代码以按顺序执行我的指令。

最佳答案

如果您的异步方法确实具有完成处理程序,则可以“序列化”或“链接”许多异步调用,如下所示:

[self asyncFooWithCompletion:^(id result){
    if (result) {
        [self asyncBarWithCompletion:^(id result){
            if (result) {
                 [self asyncFoobarWithCompletion:^(id result){
                     if (result) {
                         ...
                     }
                 }];
            }
        }];
    }
}];

当然,这与链接的异步调用的数量越来越混淆,尤其是当您也要处理错误时。

使用第三方库尤其有助于克服这些问题(包括错误处理,取消),它可能类似于以下代码:

鉴于:
- (Promise*) asyncFoo;
- (Promise*) asyncBar;
- (Promise*) asyncFoobar;

“束缚”三种异步方法,包括错误处理:
[self asyncFoo]
.then(^id(id result){
    ... // do something with result of asyncFoo
    return [self asyncBar];
}, nil)
.then(^id (id result){
    ... // do something with result of asyncBar
    return [self asyncFoobar];
}, nil)
.then(^id(id result) {
    ... // do something with result of asyncFoobar
    return nil;
},
^id(NSError*error){
    // "catch" any error from any async method above
    NSLog(@"Error: %@", error);
    return nil;
});

有关“ promise ”的一般信息,请阅读Wiki文章Futures and Promises

有许多实现Promise的Objective-C库。

10-08 01:18