3
votes

I have an issue with firebase 1.1.0 for Unity SDK.

As soon as I activate firebase by FirebaseApp.DefaultInstance.SetEditorDatabaseUrl( myurl ) all Tasks not generated by firebase are executed on the main thread. So I can retrieve and post data to firebase just fine and even process it in tasks. They run on separate thread, which I see when debugging. However when I will use Task.Run( MyComputingFunction ) in the Start method of some MonoBehaviour the Unity hangs. Assume that this function just counts from 0 to 999999 so it is not a locking problem. For the time of calculation Unity freezes because the task is executed on the main thread. If I will comment out firebase activation my task will run in separate thread and will not freeze Unity.

Please help.

Here is a minimal working example. Attach it to a game object and observe tasks running parallel. Uncomment pointed line and tasks will execute in linear order.

using UnityEngine;
using System;
using System.Threading.Tasks;
using Firebase.Unity.Editor;
using Firebase.Database;

public class NetworkController : MonoBehaviour
{
    public static DatabaseReference @ref;

    void Start()
    {
        // Uncomment line below
        //InitializeDatabase();
        TestStuff();
    }

    private void TestStuff()
    {
        Task.Run( Counter(1) );
        Task.Run( Counter(2) );
        Task.Run( Counter(3) );
    }

    private Action Counter( int i )
    {
        return delegate {
            int a = 0;
            while ( a + 10 < 900000 ) {
                a++;
                if ( a % 5000 == 0 )
                    Debug.Log( a + i);
            }
        };
    }

    private void InitializeDatabase()
    {
        Firebase.FirebaseApp.DefaultInstance.SetEditorDatabaseUrl( "https://dinosaur-facts.firebaseio.com/" );

        @ref = FirebaseDatabase.DefaultInstance.RootReference;
    }
}
2
Can you post your code? - MichaelDotKnox
@MichaelDotKnox I've updated my post. - Heti

2 Answers

2
votes

I'm a firebase engineer and have just looked at your post. I'm sorry you hit this.

This is a bug in the UnityTask library that we rely on. What's happening is that the task library is mis-using SynchronizationContext.Current (when set) as a vehicle to launch tasks. Task.Run should always use the threadpool and not ever SynchronizationContext.Current. SynchronizationContext.Current is meant to be used to marshal calls from other threads.

I will investigate fixing this on our side. I do have a workaround for you to use in the meantime.

TaskFactory factory = new TaskFactory(new TaskScheduler(null)); //null = threadpool.
factory.StartNew(() => myFunction());
0
votes

(I'm an engineer from the firebase C++ / Unity team.)

I believe we fixed this in a past release. https://firebase.google.com/support/release-notes/unity#4.0.3

Recently we just released 4.3.0 and since this was reported several more improvements and fixes have been made with threading and Tasks.