I try to make a windows desktop application in C # and what I'm trying to do is have a button that activates a thread that shows an infinite loop in a listbox that can be stopped with another button, I'm new to threads so I do not know how to start.
namespace WindowsFormsApp1
{ public partial class Form1: Form { public int counter = 0; public bool IsRunning = false; public List oThreads = new List ();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Thread oThread = new Thread(new ThreadStart(ImportStart));
//oThread.SetApartmentState(ApartmentState.STA);
//oThread.Name = "Main Thread";
//oThread.IsBackground = true;
//oThread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
// IsRunning = !IsRunning;
Thread t = new Thread(new ThreadStart(ImportStart));
t.SetApartmentState(ApartmentState.STA);
t.Name = "t" + (oThreads.Count() + 1).ToString();
t.IsBackground = true;
t.Start();
oThreads.Add(t);
}
public void ImportStart()
{
while (true)
{
// if (IsRunning)
//{
this.Invoke(new MethodInvoker(delegate () {
//if (counter < 100)
// label1.Text = (counter++).ToString();
label1.Text = oThreads.Count().ToString();
//listBox1.Items.Add(oThreads.Count().ToString());
//listBox1.Refresh();
//listBox1.DoubleClick += new EventHandler(ListBox1_DoubleClick);
}));
// Thread.Sleep(500);
//}
Thread.Sleep(100);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (oThreads.Count > 0)
{
oThreads.Last().Abort();
oThreads.RemoveAt(oThreads.Count() - 1);
}
}
private void ListBox1_DoubleClick(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
if (oThreads.Count > 0)
{
for (int n = oThreads.Count() -1; n>= 0; n--)
{
string removelistitem = listBox1.SelectedItem.ToString();
if (listBox1.Items[n].ToString().Contains(removelistitem))
{
oThreads.Last().Abort();
oThreads.RemoveAt(oThreads.Count() - 1);
}
}
//oThreads.Last().Abort();
//oThreads.RemoveAt(oThreads.Count() - 1);
}
}
}
}
}