简体   繁体   中英

dispatch_async is being fired 10 times

As I have mentioned in the title, my dispatch_async is firing 10 times. And I use it to make the GUI more responsive. But when it fires 10 times it is taking a very long time to do all the things it has to do. Here's the code:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    [self calculateAllThatShizzle];
});

And the calculateAllThatShizzle method has about 150 lines of only calculations(including many loops).

I did try the following:

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    [self calculateAllThatShizzle];
});

But then it seems like it is only used once for the whole lifecycle and I need to fire it every time the page is shown.

So the question is: how can I force the dispatch_async to fire only once?

Any help would be appreciated, thank you

EDIT

These dispatch_async and dispatch_once are in checkAndCalculateIfNecessary method. And this method is called from the PageControl like that:

- (void)scrollViewDidScroll:(UIScrollView *)sender {
  // We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
  // which a scroll event generated from the user hitting the page control triggers updates from
  // the delegate method. We use a boolean to disable the delegate logic when the page control is used.
  if (pageControlUsed) {
    // do nothing - the scroll was initiated from the page control, not the user dragging
    return;
  }
  // Switch the indicator when more than 50% of the previous/next page is visible
  CGFloat pageWidth = scrollView.frame.size.width;
  int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
  pageControl.currentPage = page;

  DetailViewController *controller = [viewControllers objectAtIndex:page];
  [controller saveTheValues];

  // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
  [self loadScrollViewWithPage:page - 1];
  [self loadScrollViewWithPage:page];
  [self loadScrollViewWithPage:page + 1];

  if ((page + 1) == kNumberOfPages) {
    [controller checkAndCalculateIfNeccessary];
  }
}

I think that's happening because scrollViewDidScroll: method being called multiple times as user scrolls content, try calculations in – scrollViewDidEndDecelerating: and/or make a bool value to control if calculations should fire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM