Tengo una aplicación Unity para Android que recibe datos de un servidor (secuencia de comandos de Python) que lee datos de forma asíncrona. El subproceso principal de Unity se congela si en algún momento no hay datos para leer, cuando lee datos, el subproceso principal se descongela. Intenté poner NetworkStream.DataAvailable como condición y/o bucle, pero el problema persiste.
Debajo del código:
void Start() { Client().WrapErrors(); { async Task Client() { while (!IsConnected(client)) { try { client = new TcpClient(host, port); s = client.GetStream(); while (true) { if (s.DataAvailable) { Debug.Log("1 await Task.Delay(TimeSpan.FromSeconds(1.0f));"); await Task.Delay(TimeSpan.FromSeconds(1.0f)); s.ReadTimeout = 10; Debug.Log("myCompleteMessage = (JSONNode)await ReadPacket(s);"); myCompleteMessage = (JSONNode)await ReadPacket(s); // Other stuff after reading } } } } }Paquete de lectura
async Task<JSONNode> ReadPacket(Stream s) { var buffer = new byte[131072]; // Read 4 bytes (we will assume we can always read that much) var n = s.Read(buffer, 0, 4); if (n < 4) throw new Exception("short read"); var fileSize = BitConverter.ToUInt32(buffer, 0); Debug.Log("Reading a blob of length" + fileSize.ToString()); // Memory stream to accumulate the reads into. var ms = new MemoryStream(); while (ms.Length < fileSize) { // Figure out how much we can read -- if we're near the end, // don't overread. var maxRead = Math.Min(buffer.Length, fileSize - ms.Length); var increment = await s.ReadAsync(buffer, 0, (int)maxRead); // ... and write them into the stream. ms.Write(buffer, 0, increment); Debug.Log("Read" + ms.Length + "of" + fileSize); } Debug.Log("Loop Read ended " + fileSize); // Decode the bytes to UTF-8 and parse. return JSONNode.Parse(Encoding.UTF8.GetString(ms.GetBuffer())); }No sé/no encuentro WrapErrors , pero parece que esta llamada hace que su tarea se ejecute sincrónicamente.
En tal caso, creo que preferirías usar, por ejemplo
Start() { Task.Run(()=> Client().WrapErrors()); } Opinión personal: para algo que se supone que debe continuar para siempre (o por un tiempo), preferiría usar un Thread adecuado en lugar de una Task .
Cuando usa Task , generalmente espera que devuelva algo en algún momento. Además, se pueden nombrar los subprocesos, lo que puede ser útil durante la depuración.
Finalmente, no sé cómo está manejando los resultados, ¡pero asegúrese de devolverlos de alguna manera al hilo principal! La mayor parte de la API de Unity solo puede ser utilizada por el subproceso principal de Unity.