How to properly handle custom networking? (Threading)

I’m using C# for my game, so I guess what I’m looking at is the System.Threading header, and creating a new thread; however there’s a problem that I can’t seem to resolve.

Here’s my BASIC Script for the client; I’m using a UDP Server for the time being (More or less a project for school)

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class ServerConnection : MonoBehaviour 
{	
	protected static UdpClient Client;
	
	public static byte[] MessageData;
	
	static ASCIIEncoding Encoding;
	
	
	void Start()
	{
		Client = new UdpClient();
		Encoding = new ASCIIEncoding();
		new Thread(new ThreadStart(ReceiveData)).Start();
	}
	
	/**
	 * Recieve the data and get the packet ID, create a handle packet script (static) that uses the ID
	 * as a parameter; Create Static Packets
	 **/
	
	void ReceiveData() 
	{
		while(true)
		{
			Debug.Log ("true");
		}
	}
	
	public static void SendData(string packetId, string data)
	{
		MessageData = Encoding.GetBytes(packetId+data);
		Client.Send(MessageData, MessageData.Length, new IPEndPoint(IPAddress.Loopback, 9955));
	}
}

Ignore the static networking, please; I’m used to Java and not exactly sure how to cross-reference without creating static variables in C# (and not creating a new instance)

=====================================

Problem:

When I run the program, it runs like it should, spamming the console with the string “true”, however when I close the game, the thread continues to run, that’s not all, I can also no longer start the game again without restarting the editor. Trying to figure out a way around this, or maybe even… a more proper way to do this.

The thread is going to be used to receive data from the server, and using it on the main thread (in the update) causes deadlocks when data isn’t being received.

while(true) <------- What does this mean ?

{

Debug.Log (“true”);

}

Threading is not really supported in Unity, it’s more like just about tolerated. This means that you need to do more housekeeping yourself than usual - including detecting when Play mode is exited in the editor and killing your threads. The best way I know to do that is to implement a void OnApplicationQuit method, test Application.IsEditor(), and if so, tidy things up.

Ahhh, Alright; Makes sense.

I was thinking about using ApplicationQuit handles, but I didn’t know if they would work in the editor.

Also

While(true) basically means always.

First of all, threading is fully supported in Unity, this is just pure FUD. Second of all, ApplicationQuit does not fire in the editor.

The way i have solved this in my networking lib is like this:

using UnityEngine;

[FpsExecutionOrder(2000)]
public class FpsAppUnityEvents : MonoBehaviour {
    void Start () {
        DontDestroyOnLoad(gameObject);
    }

    void OnDestroy () {
        if (Application.isEditor) {
            FpsCallbacks.AppShutdown();
        }
    }

    void OnApplicationQuit () {
        FpsCallbacks.AppShutdown();
    }
}

It wasn’t meant to be FUD, just a light-hearted way of saying that while you can use threading in your code, Unity doesn’t help you with it as much as it usually does.

OnApplicationQuit is indeed called in the editor on leaving play mode, but your use of OnDestroy is probably better as it also covers other cases where the MonoBehaviour is being destroyed.

It is not called, try it out yourself.

I did, and it was called.

I don’t want to fight about this though, I agree that OnDestroy is better.

OnApplicationQuit() fires in the editor (4.3.0.f4 at least) if you stop playing. It doesn’t when you edit code and it just recompiles.

sup·port
səˈpôrt/
verb
past tense: supported; past participle: supported

bear all or part of the weight of; hold up.
“the dome was supported by a hundred white columns”
synonyms: hold up, bear, carry, prop up, keep up, brace, shore up, underpin, buttress, reinforce, undergird More
“a roof supported by pillars”
produce enough food and water for; be capable of sustaining.
“the land had lost its capacity to support life”
be capable of fulfilling (a role) adequately.
“tutors gain practical experience that helps them support their tutoring role”
endure; tolerate.
“at work during the day I could support the grief”

give assistance to, esp. financially; enable to function or act.
“the government gives $2.5 billion a year to support the activities of the voluntary sector”
synonyms: help, aid, assist;

By this definition, most would say that user threads are supported by Mono. Unity doesn’t prevent it, but it sure as hell isn’t giving you any assistance, and in fact is fairly cumbersome to interact with from your own threads.

I’d also say that threads aren’t fully supported by the current Mono implementation given how much more support you get in non-ancient versions of .NET.