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();
}
}