- Home /
Threading with UDPClient - Editor Freezing
I'm trying to understand the relationship between Unity and Mono Threads and have found this useful: http://answers.unity3d.com/questions/180243/threading-in-unity.html ,
Now, I'm trying to use a Thread to read from a UDP socket. This works fine the first time I hit play in the editor but upon hitting play a second time, the editor freezes.
Here's a minimal script that you can use to reproduce the issue in an empty scene.
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDP_ThreadTest: MonoBehaviour {
Thread receiveThread;
UdpClient client;
// -------------------------------------------------------------------------
public void Start()
{
init();
}
// -------------------------------------------------------------------------
private void init()
{
receiveThread = new Thread(
new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
print("Start");
}
// -------------------------------------------------------------------------
private void ReceiveData()
{
int somePort = 6390;
try {
client = new UdpClient(somePort);
while (Thread.CurrentThread.IsAlive)
{
// do stuff
}
} catch(Exception e) {
}
}
// -------------------------------------------------------------------------
public void OnApplicationQuit()
{
// end of application
if (receiveThread != null)
{
receiveThread.Abort();
}
print("Stop");
}
}
Download and change ext to .cs
Just attach it to the camera, hit play, hit stop, and then hit play again. At that point the editor should freeze.
My questions: Why is this causing the editor to freeze and what's the correct thing to do here?
Answer by tobiass · Jul 31, 2012 at 08:39 PM
Without a Thread.Sleep(x), your thread will run on highest frequency. I would check if OnApplicationQuit() is called when you run this in the editor and then stop. If the Thread doesn't end, the port you use will be used and that might block Unity somehow.
OnApplicationQuit is being called and I've tried using sleep with no change.
I just tried this again and it seems to work... I also put a receiveThread.Join() after the abort to be sure.
Answer by arckex · Feb 25, 2014 at 07:52 PM
I solved this with only a
void OnApplicationQuit() { receiveThread.Abort(); if (client!=null) client.Close(); }
on my
Thread receiveThread; UdpClient client;
and no Thread.Sleep()