- Joined
- Jan 13, 2008
- Messages
- 2,303
- Reaction score
- 6
- Points
- 38
- Location
- Atlanta, GA, USA, North America
I'm working on a simple C# program that can send and receive ORB:Connect information. However, I'm having a small problem with getting my program to exit properly. Currently, it's setup as a Windows Form application, so in order to continuously receive data, I've spun receiving the information into its own little thread. However, that thread never seems to terminate, and the program hangs on exit. Here's my code pretty much in its entirety:
In the form closing method, I set the bool to true so the while loop (in the receive method) should stop, and the thread should close the things, then exit. But it doesn't seem to, as I said, it hangs up on closing and I have to to "Stop Debugging" from the menu. Any idea what I'm missing here?
Thanks!
Code:
public partial class Form1 : Form
{
public delegate void myDelegate(string aString);
myDelegate set;
TcpClient client;
StreamReader reader;
Thread rThread;
private volatile bool stop = false;
public Form1()
{
this.FormClosed += Form1_FormClosing;
InitializeComponent();
client = new TcpClient();
client.Connect("127.0.0.1", 37777);
set += new myDelegate(this.setText);
rThread = new Thread(new ThreadStart(receive));
//rThread.IsBackground = true;
rThread.Start();
}
~Form1()
{
stop = true;
}
public void receive()
{
reader = new StreamReader(client.GetStream());
while (!stop)
{
set(reader.ReadLine());
Thread.Sleep(1);
}
reader.Close();
client.Close();
}
private void Form1_FormClosing(object sender, EventArgs e)
{
stop = true;
rThread.Join(2000);
}
private void button1_Click_1(object sender, EventArgs e)
{
StreamWriter writer = new StreamWriter(client.GetStream());
writer.WriteLine(textBox2.Text);
writer.Flush();
}
private void setText(string s)
{
if (this.textBox1.InvokeRequired)
{
myDelegate ss = new myDelegate(setText);
this.Invoke(ss, new object[] { s });
}
else
{
textBox1.Text = s;
//textBox1.AppendText(s + "\r\n");
//textBox1.SelectionStart = textBox1.Text.Length;
}
}
}
Thanks!