System.Thread.Abort() not working

Hello

When i start background Thread i cannot Abort it why? Unity just freezes next time when i start scene again. How i can fix this?

[edited]

public class Main : MonoBehaviour
{
    Thread t;
    void Start()
    {
        t = new Thread(ts);
        t.Start();
        Debug.Log("good");
    }
    void ts()
    {

        TcpListener ts = new TcpListener(IPAddress.Any, 5300);
        ts.Start();
        Socket sct = ts.AcceptSocket();

    }
    void OnApplicationQuit()
    {
        t.Abort();
        Debug.Log(t.IsAlive); //true (must be false) 
    }
}

Your thread code is horror for the computer I fear.
If you have a permanent background thread, then having thread sleep in is a must have.

Thread t; 
    void Start() 
    { 
        Thread t = new Thread(startThread); 
        t.IsBackground = true; 
    }

Issue here is that you are making a local Thread t, along with your global Thread t, so which do you think is running?

The global or the local?
And dreamora is right, in your While loop, add a sleep in there of a milisecond or so. If you don’t the process will never yield instruction back to the parent thread.

thanks for fast reply! =)

ok, i fixed it, that was mistake sorry=)

“while(true)” it is just example , there can be any code like sync sockets.

Still i have this question. why Abort() method not working?

Sorry for my bad english=)

Put a try/catch statement in there, check thread state, if thread state running then call thread abort, you can check to see if the thread IsAlive also, which really is an overload for thread state, if t.IsAlive == true, then the thread is starting and running normally, so you can call t.Abort, otherwise you got something else going on.

It is very hard to help troubleshoot when we are seeing incomplete non functional code. Could be anything going on, an infinite loop, no sleep calls, the thread isn’t running so t.Abort is throwing an exception error which isn’t being handled, etc.

EDIT(yea your code isn’t even calling t.Start())

Your abort doesn’t work because your thread isn’t running and abort is throwing an exception.

Sorry again =) i got this bug yesterday so i tried to write it without opening unity.

Ok. Now i tested and realized that with Thread.Sleep(100); it is working.
But with sync Sockets its not
my point actually is get working sync Sockets=)

there is new tested code, that freezes unity

public class Main : MonoBehaviour
{
    Thread t;
    void Start()
    {
        t = new Thread(ts);
        t.IsBackground= true;
        t.Start();
        Debug.Log("good");
    }
    void ts()
    {

        try
        {
            TcpListener ts = new TcpListener(IPAddress.Any, 5300);
            ts.Start();
            Socket sct = ts.AcceptSocket();
        }
        catch { }

    }
    void OnApplicationQuit()
    {
        if (t != null)
        {
            t.Abort();
            Debug.Log(t.IsAlive); //true (must be false) 
        }
        else Debug.Log("t is null");
        
    }
}

Am not at home yet, so please forgive any untested syntax on my part, so this is from the “hip” as it where. Absolutely no testing from me right now, am helping by programming straight in this discussion thread.

public class Main : MonoBehaviour 
{ 
    Thread t; 
    ThreadStart tDelegate;
    TcpListener ts;
    Socket sct;
    void Start() 
    {   
        tDelegate = new ThreadStart(ts);
        t = new Thread(tDelegate); 
        t.Start(); 
        Debug.Log("good"); 
    } 
    void ts() 
    { 
        ts = new TcpListener(IPAddress.Any, 5300); 
        ts.Start(); 
        sct = ts.AcceptSocket(); 
        Debug.Log("Successful start at this point");
        Thread.Sleep(100);
    } 
    void OnApplicationQuit() 
    { 
        if (t.IsAlive)
        {
            t.Abort(); 
            Debug.Log(t.IsAlive); //true (must be false)
        } 
        else
        {
            Debug.Log("Dead duck on Thanksgiving table");
        }
    } 
}

FYI this isn’t all you need to do to use the TcpListener Async if that is what you are trying to accomplish, let me know if that is what you are truely trying to do.

Thanks zumwalt, but Thread.IsAlive still returns True :frowning:

I have own .net network engine that using synchronized sockets. it is hard to rewrite everything to async sockets=).

public class Main : MonoBehaviour
{
    Thread t;
    ThreadStart tDelegate;
    TcpListener ts1;
    Socket sct;
    void Start()
    {
        
        tDelegate = new ThreadStart(ts);
        t = new Thread(tDelegate);
        t.Start();
        Debug.Log("good");
    }
    void ts()
    {
        ts1 = new TcpListener(IPAddress.Any, 5300);
        ts1.Start();
        sct = ts1.AcceptSocket();
        Debug.Log("Successful start at this point");
    }
    void OnApplicationQuit()
    {

        if (t.IsAlive)
        {
            t.Abort();
            Debug.Log(t.IsAlive); //true (must be false) 
        }
        else
        {
            Debug.Log("Dead duck on Thanksgiving table");
        }
    }
}

Am home, pulling out my tcp/ip net sockets code and Unity on Windows, going to look at this right now.

Edit: see if this stuff helps, see attached project, it is a VS 2008 project, and I have included a Unity project with it, the Unity project should work fine on the Mac and the visual studio 2008 on a PC.

EDIT:
Updated, no bugs as far as I know, some left over delegates which will be used later so I left them in there anyway.

221464–8051–$unitytcpipnetwork_137.zip (1.31 MB)

That project I just slapped together quickly in just a couple of hours so it is probably not bug free, just something to get you started, I need to eat dinner now and play some PS3. See this image for results while in Unity with that thing. It is a starting point at least I think. If this doesn’t help, I am not sure how to help you. (like I said though, probably some locks I didn’t fix in the server or possibly some conversions I am not checking in the client, but this is like 2 hours or less thrown together while taking care of kids, animals, house, etc, so more like 45 minutes of work)

I am cleaning up the code for this thing and also making a windows client to go with it, will post a cleaner build tonight.

Thanks much zumwalt for this sample.
Seems that async sockets works in unity.
How you add .net dll references in Unity?

I checked your code and found that you used here TcpListener.Stop()
i tried use in Unity but i got crash

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

public class Main : MonoBehaviour
{
    Thread t;
    ThreadStart tDelegate;
    TcpListener ts1;
    Socket sct;
    void Start()
    {
        
        tDelegate = new ThreadStart(tstart);
        t = new Thread(tDelegate);
        t.Start();        
    }
    void tstart()
    {
        ts1 = new TcpListener(IPAddress.Any, 5300);
        ts1.Start();
        sct = ts1.AcceptSocket();        
    }
    void OnApplicationQuit()
    {
        ts1.Stop(); //crash
    }
}

Well, if you have a .Net dll that is compiled with 2.0 framework in mind, simply drag and drop the DLL into the root of the assets folder, then add a Using statement at the top like you would normally in C#. At that point you can use the DLL.

If you take a look at the LinkSyncSRC.cs file, you will see that at the top I have the following:

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using UnityTCPIPLib;
using System.Security.Permissions;
using System.Threading;

The permissions one isn’t used in this example so you can forget that one if you want.

Now on into the core code:

   Connector test; // member of the UnityTCPIPLib
   string lastMessage; // what we have received last
   public Transform PlayerCoord; // transform position of target object

   void Start()
   {
     test = new Connector(); // our guts and glory
     Debug.Log(test.fnConnectResult("localhost", 10000, "Test User"));
     // localhost obvious, 10000 port, Test User player name
     if (test.res != "")
     {
        Debug.Log(test.res);// how did we do
     }
   }

At this point, I have made a connection to the server, passed it some info, and received an ACK back so I know things are working. Sockets are not the most effecient way to do things but hey. So now after I do some key checking, passing test data back and forth from Unity, when you close Unity:

void OnApplicationQuit()
{
   try { test.fnDisconnect(); }
   catch {}
}

Notice something here, I am ignoring any errors spit back at me. There is a purpose to this madness, you see, when you close the socket connection, or make a call to have it do this, you are not guaranteed that it happens immediately so the socket remains open and locked for a short period of time, but that time will exceed a game loop duration. And we really don’t need to care.

When we shut down the listener in Unity, you need to wrap it in a try/catch because the listener can delay on shutting down and Unity won’t take that into consideration when the Editor tries to terminate the thread. The Editor is non-bias on this, it has no care about your threads at-all and no way for Unity to know or understand threads you create.

So in essance, for a moment, we are orphaning the thread but the call to terminate it is queued up in windows message queu and will eventually trigger (rather short time, but enough to make Unity puke), change your code to:

 void OnApplicationQuit() 
    { 
       try
       {
        ts1.Stop();
       }
       catch(Exception e)
       {
          Debug.Log(e.ToString());
       }
    }

Then look at the log, most likely you will have a error related to a lock state call, which is safe to ignore. I have updated the code some today for VS 2008 client/server/DLL, and have been testing it locally. I will test it against Unity in the next few hours and add some more outputs in the editor and post up the new build / code and screenshots. Hopefully it will be pretty straight forward.

I wouldn’t recommend using this for anything over 4 players though and most certainly nothing with massive amounts of data back and forth, I have seen as much as 120ms delay between the player announce himself to the server, the server broadcast that player attaching to all connected and those connected refresh their player list with that new player.

Although that could simply be my dev machine.
Let me know if any of this information helps.

Ok, latest and final build has been posted to the threads [scroll up and get it from the same post as the previous build], this build does many things for you and you can use it as a building block shell. I have included a total of 3 project in the solution and I have included a Unity package also that uses it. Make sure that the Transform is attached to the main camera or some object, and make sure you give a value to the PlayerName in the inspector. Unity should -not- crash with this build. Also, I included not only the server, but a windows client that uses it, so you can start the server, then start Unity, then start the Windows Client and they will communicate.

Frankly networking with Unity doesn’t get much simpler than this shell. And this should work just as easily with Unity vs Unity Pro, should work without Pro. The Unity piece should also work on a Mac, so let me know if it doesn’t, just interested to see how this works for people who are wanting to go down the shivers TCP/IP Sockets path.
Here is a screen shot of what I am talking about:

this not work, but i found why unity crashes.

if you throw exception in non STAThread

public class Main : MonoBehaviour
{
    Thread t;
    ThreadStart tDelegate;        
    void Start()
    {        
        tDelegate = new ThreadStart(tstart);
        t = new Thread(tDelegate);
        t.Start();        
    }    
    void tstart()
    {
        throw new Exception(); //unity editor crash
    }    
}

Have you downloaded the ZIP a few posts up:
UnityTCPIPNetwork.zip ← scroll up to grab it, somewhere around the middle of page 1 of this thread

I have a script file in that zip for Unity that you should really take a look at, I am pretty confident that once you look through that script file you will see how to start your own threads in Unity and terminate them normally without Unity crapping out. You have to have things placed in the right areas and called in certain order or else you will blow up Unity.

All your thread does here, is throw up an error “while” it is running, which terminates that thread abnormally and thus in the Editor, Unity has no clue what just happened because the exception was not handled at all. An unhandled thread error like this will always make Unity puke.

I spent a few minutes to make this even easier, see attached document on threading with Unity, probably a good education entry for UniKnowledge, who knows.

This script you attach to ANY game object and make sure you set the player to run in background, then click on Windows, Console so you can see the console window and watch it!

Hit play, watch, then hit play again to stop and see termination of thread, no crash and no errors.

222593–8065–$simplethreadmodel_587.cs (4.68 KB)

Hi, i’,ve read all the post and used that code, of course when i’m trying to move the camera using values from socket, unity crahses, i’m not that much into this stuff, could somebody help me handling this threads ?

Hi zumwalt i download ur server and client unity application and i run it…

first look there is no error unity log printed Connection success and Listener Started , and unity server example print Listener Started but i cant send any message to unity or windows client application !

please help me and pardon me for bad English writing …

zumwalt, great example, thanks, but i am also having problems with broadcasting messages to unity, the windows form and server boradcast just fine, but the unity app does not recieve the bradcast :frowning: any help on this issue?