Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run an anonymous block on a specific background thread

At first glance it seemed like an easy question, but I just can't figure how to run an anonymous block on a certain background thread i.e. I am looking for the blocks equivalent of -performSelector:onThread:withObject:waitUntilDone:.

Related: Is it possible to associate a dispatch queue with a certain background thread, just like the main queue is associated with the application's main thread?

Edit Clarified that I am looking to run an anonymous block

like image 704
Chaitanya Gupta Avatar asked Dec 05 '11 07:12

Chaitanya Gupta


People also ask

How do I run a background thread?

To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread. Once you've created a Handler , you can then use the post(Runnable) method to run a block of code in the corresponding thread.

What is the best way for performing tasks on a background thread in Kotlin?

So in your Kotlin programs, performing heavy operations like network calls, interacting with Database/Device file system, etc, etc. You need to execute those tasks in the background thread. That's means you should consider using the Asynchronous approach.

Why should you avoid to run non UI code on the main thread?

If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.


2 Answers

I saw this function RunOnThread() recently in Mike Ash's PLBlocksPlayground (zip file, see BlocksAdditions.m):

void RunOnThread(NSThread *thread, BOOL wait, BasicBlock block)
{
    [[[block copy] autorelease] performSelector: @selector(my_callBlock) onThread: thread withObject: nil waitUntilDone: wait];
}

This is what I was looking for.

There are a bunch of other very useful blocks related utilities in PLBlocksPlayground, most of which Mr. Ash explains in this post.

like image 145
Chaitanya Gupta Avatar answered Sep 29 '22 10:09

Chaitanya Gupta


If I understand you right you should do this:

dispatch_queue_t thread = dispatch_queue_create("your dispatch name", NULL);
dispatch_async(analyze, ^{
    //code of your anonymous block
});
dispatch_release(thread);

You also can write some method, which will take block to it, but you should know what type of parameters will it holds:

-(void)performBlock:(void (^)(SomeType par1, SomeType par2))block ToData:(Sometype)data;

You can call it with anonymous block:

[something performBlock:^(SomeType par1, SomeType par2){
  //do your stuff
} ToData: data] 

And in method you can call your block as a simple C function:

block(par1, par2);
like image 36
igofed Avatar answered Sep 29 '22 10:09

igofed