Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
¿Se congela el subproceso principal de Unity con NetworkStream.ReadAsync?

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())); }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!