SORU
10 AĞUSTOS 2012, Cuma


Uyumsuz iki blok kadar beklemek önce başka bir blok başlangıç yürütülür

GCD kullanırken, iki uyumsuz bloklar ve yürütme sonraki adımlara geçmeden önce idam bitene kadar beklemek istiyoruz. Bunu yapmanın en iyi yolu nedir?

Aşağıdaki denedik ama işe yaramıyor:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block1
});


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block2
});

// wait until both the block1 and block2 are done before start block3
// how to do that?

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block3
});

CEVAP
3 Ocak 2014, Cuma


Genişleyen Jörn Eyrich cevap (upvote onun cevabı ver upvote bu), yoksa kontrol dispatch_async aramalar için blok olarak belki dava için zaman uyumsuz tamamlama bloklar kullanabilirsiniz GCD grupları kullanarak dispatch_group_enter dispatch_group_leave doğrudan.

Bu örnekte olduğu gibi computeInBackground biz bir şey değiştiremezsiniz (düşünün bir temsilci geri arama, NSURLConnection completionHandler, ya da her neyse), ve böylece erişimi yok gönderme çağırır.

// create a group
dispatch_group_t group = dispatch_group_create();

// pair a dispatch_group_enter for each dispatch_group_leave
dispatch_group_enter(group);     // pair 1 enter
[self computeInBackground:1 completion:^{
    NSLog(@"1 done");
    dispatch_group_leave(group); // pair 1 leave
}];

// again... (and again...)
dispatch_group_enter(group);     // pair 2 enter
[self computeInBackground:2 completion:^{
    NSLog(@"2 done");
    dispatch_group_leave(group); // pair 2 leave
}];

// Next, setup the code to execute after all the paired enter/leave calls.
//
// Option 1: Get a notification on a block that will be scheduled on the specified queue:
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSLog(@"finally!");
});

// Option 2: Block an wait for the calls to complete in code already running
// (as cbartel points out, be careful with running this on the main/UI queue!):
//
// dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // blocks current thread
// NSLog(@"finally!");

Bu örnek,: tamamlama computeİnBackground: uygulanır:

- (void)computeInBackground:(int)no completion:(void (^)(void))block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSLog(@"%d starting", no);
        sleep(no*2);
        block();
    });
}

Çıkış (çalışma zaman damgaları ile):

12:57:02.574  2 running
12:57:02.574  1 running
12:57:04.590  1 done
12:57:06.590  2 done
12:57:06.591  finally!

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Adam Outler

    Adam Outler

    19 EKİM 2006
  • Dive In

    Dive In

    17 Temmuz 2013
  • The CGBros

    The CGBros

    20 AĞUSTOS 2011