Question

As title implies. Yes, i know it's horribad to use .abort() but hear me out

I'm using 2 threads, The main thread (of my app) and a socket listen thread (familiar sound anyone?) Instead of using asynchronous .AcceptAsync() calls (tbh, main reason is that i haven't looked too much into them), I have the thread just hang on socket.Accept(); Ofcourse, when i call thread.Abort(), the thread doesn't close because it's still waiting for a connection, once it passes Accept() it'll abort just fine.

Code:

    void listenserver()
    {
        while (run)
        {
            fConsole.WriteLine("Waiting for connections..");
            connectedsock = mainsock.Accept();
            connected = true;
            fConsole.WriteLine("Got connection from: " + connectedsock.RemoteEndPoint);

... and elsewhere:

    private void button_start_Click(object sender, EventArgs e)
    {
        if (!run)
        { //code ommitted.
        }
      else
        {
            run = false;
            listenthread.Join(3000);
            if (listenthread.IsAlive)
            {
                fConsole.WriteLine("Force-closing rogue listen thread");
                listenthread.Abort();
            }
            button_start.Text = "Start";
            groupBox_settings.Enabled = true;
        }

is there any way of assuring the thread will end, not being to stuff the whole thing in a seperate app and then ending that? Note that i DO have thread.IsBackground set to true (as suggested in other forum threads), it doesn't make any difference though.

Was it helpful?

Solution

Since you're already using a thread, you might as well just use BeginAccept. Async code doesn't need to complicate your code, since you can use lambdas like this:

var socket = new Socket(...);

socket.BeginAccept(result =>
{
    if (this.abort)
    {
        // We should probably use a signal, but either way, this is where we abort.
        return;
    }

    socket.EndAccept(result);
    // Do your sockety stuff
}, null);

Even with a separate method definition for the AsyncCallback, the code isn't complex.

By doing async IO you're also being a lot more efficient with the CPU time, since between the call to BeginAccept and EndAccept, the thread can be reused for other processing. Since you're not using it for anything purposeful while waiting for the connection, holding up a thread is pretty meaningless and inefficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top