使用Firebase数据库进行异步编程时Unity崩溃

时间:2019-06-17 16:17:07

标签: c# firebase unity3d firebase-realtime-database async-await

当我尝试执行此操作时,它会崩溃:

我想使用户数据异步,如果我不使用异步任务,它将返回null

public class Database : MonoBehaviour
{
    private DatabaseReference m_database;

    private const string DATA_URL = "hidden";

    public static Database singleton;

    void Awake ()
    {
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
        m_database = FirebaseDatabase.DefaultInstance.RootReference;

        DontDestroyOnLoad(this);
        singleton = this;
    }

    void Start ()
    {
        User user = new User();
        user = GetUserAsync("213asdasd").Result;
        Debug.Log(user.email);
    }

    public void RegisterNewUser (User user)
    {
        string jsonData = JsonUtility.ToJson(user);

        m_database.Child("Users").Child(user.id).SetRawJsonValueAsync(jsonData);
        m_database.Child("Users").Child(user.id).Child("id").SetValueAsync(user.id);

        m_database.Child("Users").Child(user.id).Child("email").SetValueAsync(user.email);
    }

    public async Task<User> GetUserAsync (string id)
    {
        User user = new User();
        await FirebaseDatabase.DefaultInstance.GetReference("Users").Child(id)
       .GetValueAsync().ContinueWith(task =>
       {
           if (task.IsFaulted)
           {
               // Handle the error...
           }
           else if (task.IsCompleted)
           {
               DataSnapshot snapshot = task.Result;
               string rawUserData = snapshot.GetRawJsonValue();
               Debug.Log(rawUserData);
               user = JsonUtility.FromJson<User>(rawUserData);
           }
       });

        return user;
    }
}

1 个答案:

答案 0 :(得分:1)

混合异步等待和阻塞调用可能会导致问题。

引用Async/Await - Best Practices in Asynchronous Programming

如果无法将代码完全重构为异步,请使用异步事件处理程序

void Start () {
    started += onStarted;
    started(this, EventArgs.Empty);
}

event EventHandler started = delegate { }
private async void onStarted(object sender, EventArgs  args) {
    started -= onStarted;
    User user = await GetUserAsync("213asdasd");
    Debug.Log(user.email);
}

代码也应始终遵循异步模式

public async Task<User> GetUserAsync (string id) {
    User user = new User();
    try {
        DataSnapshot snapshot = await FirebaseDatabase.DefaultInstance
            .GetReference("Users").Child(id).GetValueAsync();
        string rawUserData = snapshot.GetRawJsonValue();
        Debug.Log(rawUserData);
        user = JsonUtility.FromJson<User>(rawUserData);
    } catch(Exception ex) {
        // Handle the error...
    }
    return user;
}