Why is BeginBackgroundTask checking that I'm on the ui thread?

I'm getting this exception:

MonoTouch.UIKit.UIKitThreadAccessException: UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread.
at MonoTouch.UIKit.UIApplication.EnsureUIThread () [0x00023] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:70
at MonoTouch.UIKit.UIApplication.BeginBackgroundTask (System.String taskName, MonoTouch.Foundation.NSAction expirationHandler) [0x00000] in /Developer/MonoTouch/Source/monotouch/src/build/compat/UIKit/UIApplication.g.cs:238
...

Apple says that BeginBackgroundTask (well, beginBackgroundTaskWithExpirationHandler:) can be called on a non-main thread:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler:

This method can be safely called on a non-main thread.

Using:
Xamarin.iOS
Version: 8.2.0.193 (Business Edition)

Posts

  • DannyCDannyC US ✭✭✭✭

    Seems you are updating some UI component from the background thread.

  • adamkempadamkemp USInsider, Developer Group Leader mod

    I think you may be using this function for the wrong thing. The purpose of BeginBackgroundTask is to start a task that will run while the app is in the background. you are requesting permission to continue running some code after the user leaves your app. This code still happens in the UI thread.

    If you just want to run a function in a background thread while your app is still open then use the Task Parallel Library:

    Task.Factory.StartNew(SomeMethod);
    
  • bansheebanshee USMember

    BeginBackgroundTask doesn't have anything to do with launching new threads - it's all about telling iOS that you have interesting work that should continue while you're in the background. It doesn't create new threads, it just lets you get cpu cycles when you're in the background. (Well, it tells iOS that you would like to get cycles. Whether or not you actually get those cycles is up to iOS.)

    "The purpose of BeginBackgroundTask is to start a task that will run while the app is in the background." Yes, that's exactly what we need. But keep in mind that task != thread; a task here is an abstract concept that can involve work on N threads.

  • adamkempadamkemp USInsider, Developer Group Leader mod

    Yes, I know that. I thought that you were using it for something else. Now I see this:

    Apple says that BeginBackgroundTask (well, beginBackgroundTaskWithExpirationHandler:) can be called on a non-main thread

    It's probably just an incorrect binding. You should report a bug: http://bugzilla.xamarin.com

Sign In or Register to comment.