i need to terminate a background thread in winform, however, i dont know how. i know that using Thread.Abort, only creates problems..please help
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.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
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);// i am trying to 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));
Invoke(new Action(AddNameList));
}
}
public void Output()
{
ChatterScreen.Text = allMessages;
}
public string checkForName(string input)
{
string name = "";
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ':')
{
name = input.Substring(0, i);
}
}
return name;
}
List<string> names = new List<string>();
public void AddNameList()
{
if (!names.Contains(checkForName(msg)))
{
names.Add(checkForName(msg));
}
comboBox1_DataBind();
listBox2_DataBind();
}
private void listBox2_DataBind()
{
Chatters.DataSource = null;
Chatters.DataSource = names;
}
private void comboBox1_DataBind()
{
comboBox1.Items.Clear();
foreach (string item in names)
{
comboBox1.Items.Add(item);
}
}
private void button1_Click(object sender, EventArgs e)
{
sw.WriteLine(comboBox1.Text+"@2@3"+name);
sw.Flush();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
}
}
}