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
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With