Threading

From $1
Table of contents

It is possible to use multiple threads in MonoTouch applications, either directly when using System.Threading.Thread or the System.Threading.ThreadPool or indirectly when using the various asynchronous methods exposed by the API (The Begin/End pattern for delegates and APIs).

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.BeginInvokeOnMainThread, like this:

MyThreadedRoutine ()
{
    var result = DoComputation ();
    BeginInvokeOnMainThread (delegate {
        label.Text = "The result is: " + result;
    });
}

BeginInvokeOnMainThread will suspend the execution of your thread, and wait for the delegate to be executed on the main thread. When that completes, the thread resumes execution. Additionally, it is possible to use InvokeOnMainThread() to queue a delegate for invocation, but this will suspend your thread until the main thread had a change to run.

Tag page

Files (0)

 
Page last modified 13:42, 12 Aug 2010 by Miguel