create an AndroidJavaObject within a Thread

Hi, while usign System.Threading library for unity I find that this code makes the app to crash in Android:

Task.Factory.StartNew(() =>
{
var hubConnection = new AndroidJavaObject(“microsoft.aspnet.signalr.client.hubs.Prueba”);
});

(Prueba is an empty class with single property, created for the purpose just to check the HubConnection was not messing up with threads)

Any idea why?

Unity is generally not so well suited for multithreading (you have to be careful with what you do).

Regarding your issue, without seeing the exact error message, I assume this is because the thread you created is not attached to any Java VM.

From the context of your new thread, call:

AndroidJNI.AttachCurrentThread();

See the documentation for this method here: Unity - Scripting API: AndroidJNI.AttachCurrentThread

*BTW - I did not know you could use TPL (Task Parallel Library) in Unity… It uses an older Mono that did not have those libraries…