- Home /
Run return method on new thread?
I've been looking for how to do this but cannot find anything that seems to work for unity. I'm trying to simply run some methods (SQLite) that have a return on a new thread as they black the main thread for a split second (very noticeable). It works like this:
Start:
public static ObjectReference Loaditem(string ID)
{
return ObjectReferenceFromID(ID);
}
Object Reference from ID:
private static ObjectReference ObjectReferenceFromID(string ID)
{
ObjectReference or = new ObjectReference();
List<object> contents = GetTableContents("objects", ID);
if (contents.Count <= 0) return null;
or.DatabaseID = ID;
or.Name = contents[1].ToString();
or.Prefab = contents[2].ToString();
contents = GetTableContents("items", ID);
if(contents.Count > 0)
{
// Do stuff
}
contents = GetTableContents("consumable", ID);
if (contents.Count > 0)
{
// Do stuff
}
contents = GetTableContents("ammunition", ID);
if(contents.Count > 0)
{
// Do stuff
}
return or;
}
Finally the code that blocks the main thread:
private static List<object> GetTableContents(string table, string ID)
{
List<object> d = new List<object>();
_dbc.Open();
_dbcm.CommandText = "SELECT * FROM " + table + " WHERE oid = '" + ID + "'";
_dbr = _dbcm.ExecuteReader();
while (_dbr.NextResult())
{
for (int i = 0; i < _dbr.FieldCount; i++)
{
if (_dbr.GetValue(i) != null)
{
d.Add(_dbr.GetValue(i).ToString());
}
}
}
_dbc.Close();
return d;
}
Is it possible to run this in a way that does not block the main thread? (The script does not inherit monobehaviour and is started from a class that does)
Answer by nate-sewell · Aug 22, 2016 at 03:41 AM
Where's there any threading in this example? You can pass data back and forth between threads quite easily as they share the same memory space. just need to be careful of race conditions and possible deadlocks when accessing the same resources across threads.
In this simple example you could just have a boolean flag that is read in the spawning thread and only set in the new thread to let the parent know when to check a list in the object, it's simple enough that there's not a race condition, as long you just check the flag and either move on if not ready, or process the data if the flag is set. (make sure you do not set the flag until you are done with the list in the thread)
In more complex situations you need to worry about locking critical code sections. but this really doesn't rise to the level of needing that.
Answer by _Yash_ · Aug 22, 2016 at 04:29 AM
You can create Event mechanism for this, there will be a queue of integers and each int represents an event (like read success, write success, failure etc..) in update you will poll for event and based on the event you will access the result object (which will be assigned by other thread). This way there will be no race conditions and no blocking and you can have multiple types of event.