deimus
deimus

Reputation: 9883

GCD : How to check if the task is runnig

I'm running the task using following code,

mTimerForImageUpload = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (mTimerForImageUpload) {
    dispatch_source_set_timer(mTimerForImageUpload, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * uploadCheckInterval), NSEC_PER_SEC * uploadCheckInterval, leeway);
    dispatch_source_set_event_handler(mTimerForImageUpload, ^{
        [self uploadData];
    });
    dispatch_resume(mTimerForImageUpload);
}

Basically I want to have only one running instance of the uploadData method at the same time. I.e. if the task is still running I dont want to run new thread, but want to wait until it finishes.

Any ideas how to do this ?

Upvotes: 2

Views: 765

Answers (1)

David Rönnqvist
David Rönnqvist

Reputation: 56635

GCD and blocks don't support this by them selves but you could make it work.

You could either have a mutable set where the blocks add them selves when they start and remove them selves when they are finished (i.e. first and last thing they do) or go to a higher abstraction (NSOperation).

Keeping track of running blocks yourself

If you add the blocks themselves (or some unique key like the resource they are uploading) to a mutable set then you can query that set and see if that resource is already being uploaded using [runningBlocksSet containsObject:myNewBlockForResoucreThatImAboutToUpload] (sorry for the extremely long variable name).

Using NSOperation to see if isExecuting

If you on the other side choose to use NSOperations instead to do the uploads then they already support checking if they are running by using [myUploadOperation isExecuting]. You can also check if it was cancelled, is finished, or if it is ready (operations can have dependencies and are not ready to run until all operations they depend on are finished).

Upvotes: 4

Related Questions