The MonoTouch runtime gives access to developers to the .NET threading APIs, both explicit use of threads (System.Threading.Thread, System.Threading.ThreadPool) as well as implicitly when using the asynchronous delegate patterns or the BeginXXX methods.
Typically developers use threads when they need to create responsive applications and they do not want to block the main UI run loop.
In the course of execution, the Objective-C runtime will create and release objects. If objects are flagged for "auto-release" the Objective-C runtime will release those objects to the thread's current NSAutoReleasePool. MonoTouch creates one NSAutoRelease pool for every thread from the System.Threading.ThreadPool and for the main thread.
If you create your own threads using System.Threading you do have to provide you own NSAutoRelease pool to prevent the data from leaking. To do this, simply wrap your thread in the following piece of code:
void MyThreadStart (object arg)
{
using (var ns = new NSAutoReleasePool ()){
// Your code goes here.
}
}
Access to UI elements should be limited to the same thread that is running the main loop for your application. If you want to make changes to the main UI from a thread, you should queue the code by using NSObject.InvokeOnMainThread, like this:
MyThreadedRoutine ()
{
var result = DoComputation ();
//
// we want to update an object that is managed by the main
// thread; To do so, we need to ensure that we only access
// this from the main thread:
//
InvokeOnMainThread (delegate {
label.Text = "The result is: " + result;
});
}
The above invokes the code inside the delegate in the context of the main thread, without causing any race conditions that could potentially crash your application.