Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading model change in MonoTouch 6.x?

Several weeks late, but I am finally getting back to updating my MonoTouch iOS app with the new 6.0 version. For long running activities (my application makes services calls to the background and does image uploads), I use threading very similar to the examples. This all worked great until I upgraded. A typical pattern in an a Controller would look like:

protected void LogInButtonClicked(object sender, EventArgs e)
{
      NetworkActivity.Start();

      // start the request.
      ThreadPool.QueueUserWorkItem ((cb) => {

          var service = new ClientUserService();
          var result = service.Login(this.UserName.Text, this.Password.Text);

          // when done, switch back to UI.
          this.InvokeOnMainThread (() => {

              NetworkActivity.Stop();

              // do the various other things to init the app on the UI thread.
          }
      });
}

The worked great on 5.x and never crashed. And it followed the published code guidelines. But now I immediately get the exception of UUIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread. I get that on my service call line (service.Login(...)).

So... I'm not exactly sure what I'm doing wrong here. I did go back and look at some of the newer samples. Some of them are using the task library (for example https://github.com/xamarin/mobile-samples/blob/master/MultiThreading/iOSMultiThreading/Screens/MainScreen_iPhone.cs), but that shouldn't preclude this QueueUserWorkItem method.

Question: did the threading model in Monotouch have a breaking change so that the above coding pattern is no longer supported?

Thanks. JB

like image 478
James Bright Avatar asked Nov 20 '25 13:11

James Bright


2 Answers

Wrap this.UserName.Text and this.Password.Text in InvokeOnMainThread delegate. Monotouch expects that all work with UI elements is performed in the UI thread.

like image 163
Ben Novoselsky Avatar answered Nov 23 '25 01:11

Ben Novoselsky


This feature was introduced a while ago in MonoTouch 5.4 (see New Library Features, Cross-thread UI Checks).

Now this is not a threading change (the code is executed as before) but simply extra checks to ensure people are warned about a common pitfall - that was often pretty hard to debug.

There are instructions if you want the old behaviour back. However be warned that your current code is broken and, while it might work 99% of the time, it might break badly for some people (e.g. such issues are often timing dependent, changing your code or using different devices might trigger the issue).

As such I strongly suggest you to fix such issues as you find them (your users will love you for it ;-) just like Ben described.

like image 29
poupou Avatar answered Nov 23 '25 02:11

poupou