我有一個線程在Winform
。在我退出應用程序或關閉服務器控制檯應用程序後,線程繼續工作。以下是代碼:如何殺死一個線程?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
StreamReader sr;
StreamWriter sw;
TcpClient connection;
string name;
private void Form1_Load(object sender, EventArgs e)
{
connection = new TcpClient("127.0.0.1", 5000);
sr = new StreamReader(connection.GetStream());
sw = new StreamWriter(connection.GetStream());
ChatterScreen.Text = "Welcome, please enter your name";
}
private void button3_Click(object sender, EventArgs e)
{
//Thread t2 = new Thread(Reader);
//t2.IsBackground = true;
//t2.Start(connection);
ThreadPool.QueueUserWorkItem(Reader,connection);//How do i kill this thread
name = InputLine.Text;
}
string textinput;
private void button2_Click(object sender, EventArgs e)
{
textinput = InputLine.Text;
sw.WriteLine(name+":"+textinput);
sw.Flush();
}
string msg;
string allMessages;
public void Reader(object o)
{
TcpClient con = o as TcpClient;
if (con == null)
return;
while (true)
{
msg = sr.ReadLine() + Environment.NewLine;
allMessages += msg;
Invoke(new Action(Output)); // An exception is thrown here constantly. sometimes it is thrown and sometimes if i quite the server application , the winform application freezes.
Invoke(new Action(AddNameList));
}
}
public void Output()
{
ChatterScreen.Text = allMessages;
}
}
如何使用該自動復位? – 2011-02-12 15:17:23
真的很糟糕的方式來與線程交互太... – 2011-02-12 17:22:58