Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make MainThread wait till some async action is done?

I have UITableView with some content, which is loaded in asynchronous way. When user rotates the device I need to make [tableView reloadData] in -willRotateToInterfaceOrientation method. ReloadData works asynchronous in my case.

I understand that reloadData works in main thread, but it fires cellForRowAtIndexPath, which works async in my case.

So the question is how to make main thread wait till UITableView's reloadData ends.

like image 661
B.S. Avatar asked May 10 '12 13:05

B.S.


People also ask

How do I wait for async task to finish?

You will need to call AsyncTask. get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.

How do you make a thread wait for some time?

In between, we have also put the main thread to sleep by using TimeUnit. sleep() method. So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution.

How do I make a thread wait for another thread?

The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.

How do you wait for a runnable to finish?

Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() . And when your myRunnable is finish it's job, call lock.


2 Answers

You may use CFRunLoopRun to make your main thread wait until UITableView data is reloaded. After data is reloaded call CFRunLoopStop passing result of CFRunLoopGetMain as parameter.

like image 173
Mehdzor Avatar answered Nov 05 '22 21:11

Mehdzor


If you call reloadData from willRotateToInterfaceOrientation then it is called on the main thread. In fact UIViews are NOT thread safe and should only ever be dealt with from the main thread (in case for some reason someone gets the idea to call reloadData from another thread).

I think there is confusion relating to "asynchronous" as a term. Asynchronous callbacks for UI delegates like willRotateToInterfaceOrientation are called on the main thread. To be asynchronous does not necessarily mean a different thread (though running asynchronously "in parallel" does).

I would recommend reading up on the Apple documentation for NSRunLoop. It is an integral part of the way iOS apps run and is a must for app programmers to understand.

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html

like image 28
NSProgrammer Avatar answered Nov 05 '22 21:11

NSProgrammer