Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MonoTouch - Threading

A common task is to do something in the background thread, then when done, pass the results to the UI thread and inform the user.

I understand there are two common ways:

I can use the TPL:

var context = TaskScheduler.FromCurrentSynchronizationContext ();

Task.Factory.StartNew (() => {
    DoSomeExpensiveTask();
    return "Hi Mom";
}).ContinueWith (t => { 
    DoSomethingInUI(t.Result);             
}, context);

Or the Older ThreadPool:

    ThreadPool.QueueUserWorkItem ((e) => {
          DoSomeExpensiveTask();
      this.InvokeOnMainThread (() => {
             DoSomethingInUI(...);
      });
});

Is there a recommended way to go when using MonoTouch to build iOS apps?

like image 583
Ian Vink Avatar asked Nov 11 '11 01:11

Ian Vink


2 Answers

While I prefer the syntax of Task Parallel Library the ThreadPool code base is older (in both Mono and MonoTouch) so you're more likely to find documentation for it and less likely to hit a bug.

like image 97
poupou Avatar answered Sep 22 '22 08:09

poupou


According to this document, mono touch provides access to ThreadPool and Thread:

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.

http://docs.xamarin.com/ios/advanced_topics/threading

Also, you should call InvokeOnMainThread to update your UI.

like image 42
bryanmac Avatar answered Sep 22 '22 08:09

bryanmac