0

It is my first question here, so I am a bit lost (And English is not my native language). I am doing a Multhread server, and when I try to stop the TcpListener or to terminate the program with Application.Exit(), I receive the following error:

An unhandled exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dll

Pointing to the line: this.Invoke(d, new object[] { text });. I am not used to work with threads too, so can anyone show me how to close everything safely?

Thank you!

public partial class Form1 : Form
{
    public IPAddress enderecoIP;
    public TcpListener escutar;
    public List<Thread> threads = new List<Thread>();

    public Form1()
    {
        InitializeComponent();
    }

    private string ipp ()
    {
        string localIP;
        using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
        {
            socket.Connect("10.0.2.4", 65530);
            IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
            localIP = endPoint.Address.ToString();
        }
        return localIP;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            enderecoIP = IPAddress.Parse(ipp());
            escutar = new TcpListener(enderecoIP, 8001);
            escutar.Start();
            textBox1.AppendText("Servidor iniciado no endereco IP " + enderecoIP.ToString() + "\n");

            for (int i = 0; i < 100; i++) // numero maximo de clientes
            {
                Thread newThread = new Thread(new ThreadStart(iniciarServidor));
                newThread.Start();
                this.threads.Add(newThread);
            }
            this.button1.Enabled = false;
        } catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private void iniciarServidor()
    {
           try
           {
                Socket s = escutar.AcceptSocket();

                byte[] b = new byte[1000];
                s.Receive(b);


                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                string palavra = enc.GetString(b);
                string linha = "";

                foreach (char c in palavra) {
                    if (c!='*') {
                        linha += c;
                    } else {
                        this.SetText(linha+"\n");
                        linha = "";
                    }
                }

                s.Close();

            }
            catch (Exception e)
            {
            this.SetText(e.Message);
            }
    }

    private void SetText(string text)
    {
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox1.AppendText(text);
        }
    }

    delegate void SetTextCallback(string text);

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        foreach (Thread t in this.threads)
        {
            if (t.IsAlive)
                t.Abort();
        }
        this.escutar.Stop();
        Application.ExitThread();
    }
}
pid
  • 11,472
  • 6
  • 34
  • 63
pl225
  • 11
  • Welcome to SO pl225 - you might find a lot of useful information here: https://www.google.com/search?q=c-sharp+close+all+threads+safely+on+shutdown&ie=&oe=#q=c-sharp+close+all+threads+safely+on+exit – Shannon Holsinger Sep 05 '16 at 13:16
  • _"English is not my native language"_ - Based on the string "Servidor iniciado no endereco" in your code, I'll mention [Stack Overflow in Portuguese](http://pt.stackoverflow.com/) if you would prefer to get help in Portuguese rather than English. Apologies if I've mis-guessed your native language. – James Thorpe Sep 05 '16 at 13:24
  • Why the `Application.ExitThread()` call? This kills the curren thread, which is already happening since you are in the `Form1.FormClosing` method. – Maarten Sep 05 '16 at 13:25
  • Thanks @ShannonHolsinger, the first search result helped a lot. – pl225 Sep 06 '16 at 22:11
  • @JamesThorpe, thank you! I did not know there was Stack Overflow in Portuguese. when I sought on the internet for other doubts, I always found results in English. – pl225 Sep 06 '16 at 22:15
  • @Maarten, I just changed Application.ExitThread to Application.Exit. Thanks for your help! – pl225 Sep 06 '16 at 22:17
  • Do not use `Thread.Abort` !! http://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort/ – Guillaume Sep 07 '16 at 08:27

0 Answers0