简体   繁体   中英

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?

虽然我更喜欢任务并行库的语法,但ThreadPool代码库较旧(在Mono和MonoTouch中),因此您更有可能找到它的文档,并且不太可能遇到错误

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM