Async Tasks with Google Firestore freezes Unity Editor.

I’m running into a problem using Asynchronous functions that return a task when used with Firestore. I’m trying to grab a QuerySnapshot from Firestore. Since Firestore returns queries asynchronously, I read that I needed to use a Async method that returns a task of type QuerySnapshot. I have the following code.

public async Task Get2()
{
orgRef = firestoreInstance.Collection(“organizations”);

QuerySnapshot orgSnapshot = await orgRef.GetSnapshotAsync();

return orgSnapshot;
}

Calling this method freezes the editor permenantly.

public void GetFromFirestore() //pulls data from firebase (used for buttons only).
{
QuerySnapshot temp = Get2().Result;
}

I’m unsure what I’m doing wrong. This is the first time I’ve touched asynchronous tasks. Any advise would be helpful.

Have you tried using the patterns from Google’s examples? Download files with Cloud Storage for Unity  |  Cloud Storage for Firebase

Yes I have, and I have gotten those solution to output the database. If I have to, I’ll go back to their method, but I’m trying to get a return value and Visual Studio tells me I can’t return a value from anonymous functions or something. I’m not all that familiar with the limitations of anonymous functions, since I don’t make use of them much.

You can’t get a result immediately from an asynchronous operation, not without causing your game to freeze at least. That’s kind of the point. It finishes what it’s doing “sometime later”, so your code can’t expect a result immediately. You need to either use a callback function with ContinueWith or similar, or periodically check IsCompleted on the task, and only try to read the result after IsCompleted is true.

https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.continuewith?view=netcore-3.1
https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.iscompleted?view=netcore-3.1

1 Like

Ah that makes sense, thank you.