Ciao a tutti! 
Ho scritto un'applicazione (un client di una chat) che però molto spesso (circa il 50% delle volte) quando viene fatta partire (sia col debug dall'ide sia che facendo doppio click sull'icona) la finestra non compare, oppure compare ma si blocca fin dall'inizio. Altre volte invece la carica normalmente e funziona.
Ecco il codice:
codice:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace SharpChatClient1
{
public partial class Form1 : Form
{
private TcpClient client;
private bool error;
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false; //to avoid warning
error = true;
try
{
client = new TcpClient("localhost", 8086);
}
catch (SocketException ex)
{
MessageBox.Show("server down");
this.Close();
}
Thread t = new Thread(new ThreadStart(run));
t.Start();
}
private void btnSend_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(client.GetStream());
try
{
sw.WriteLine(txtMsg.Text);
sw.Flush();
}
catch (IOException ex)
{
MessageBox.Show("Messaggio non inviato correttamente!", "Sharp Chat", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
txtMsg.Text = "";
}
private void run()
{
StreamReader sr = new StreamReader(client.GetStream());
while (true)
{
try
{
txtChat.AppendText(sr.ReadLine() + "\r\n");
txtChat.SelectionStart = txtChat.TextLength;
}
catch (IOException ex)
{
break;
}
}
if (error)
MessageBox.Show("Il server è momentaneamente offline. Provare a riconnettersi più tardi.", "Sharp Chat", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
//Thread.CurrentThread.Abort();
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
error = false;
client.Close();
}
}
}
C'è qualcosa che non va nel codice che devo aggiustare? Grazie in anticipo!