简体   繁体   中英

Coroutine to run SQL in Unity3d

I'm trying to understand Unity coroutines deeper. They can block execution yielding null or wait, but they are really not new threads.

In my case Unity should read info from database, which can take some time. And this is synchronous operation . This single line of code may potentially block execution for seconds.

Part of me tells just to start new thread. But I'm wondering whether it can be achieved with Unity-style coroutines.

private IEnumerator FetchPlayerInfo(int id)
{
    // fetch player from DB
    using (var session...)
    {
            // this line is NHibernate SQL query, may take long time
            player = session.QueryOver<Player>()...;
    }

    // raise event to notify listeners that player info is fetched
}

I just don't see where to put yield. Does anyone know?

Thx in advance.

You can only return yield instructions when the control flow is in your own coroutine. If you have to run a long synchronous operation, and it has no asynchronous API (which is something to be expected from a database), then you really better off with starting another thread.

However, be aware that using other threads in Unity is a little bit tricky: you won't be able to use any of Unity's API and you'll have to check in the main thread for when the worker thread has a result ready. Consider looking at ready solutions, such as Loom .

You can think of yielding as breaking a large task into chunks. After each chunk you yield to let other things happen, then come back and do another chuck. In your case you would load X number of rows each chunk until all your data is loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM