I'm new in C # and I am developing a windows application in which I have a method that should be executed asynchronously, some tasks that this method has is to update some controls in the form. For this I am using a thread with an Invoke method to update the control that belongs to the form. This form has a button that starts this thread and one that should stop it. The problem is that because the use of the Invoke method the main thread, which is the form, is blocked until the other thread to finish, so I can not click on the button that stops the thread.
Below is a program that I created to try this. It has a class that adds the numbers from 1 to 100 in a listbox.
Main program.
private Thread thrAdicionarItens;
private clcInvoke clcInvokeObject;
private void btnExibir_Click(object sender, EventArgs e) {
clcInvokeObject = new clcInvoke(lstItens);
thrAdicionarItens = new Thread(new ThreadStart(clcInvokeObject.AdicionarItens));
thrAdicionarItens.Start();
}
private void btnParar_Click(object sender, EventArgs e) {
try {
thrAdicionarItens.Abort();
}
catch (Exception) {
}
}
Class code
class clcInvoke
{
private ListBox lstItens;
private delegate void dlgAdicionarItens();
public clcInvoke(ListBox lstItens) {
this.lstItens = lstItens;
}
public void AdicionarItens() {
try {
if (lstItens.InvokeRequired == true)
lstItens.BeginInvoke(new dlgAdicionarItens(AdicionarItens));
else
for (byte contador = 1; contador <= 100; contador++) {
lstItens.Items.Add(contador.ToString());
lstItens.Update();
Thread.Sleep(100);
}
}
catch (Exception) {
}
}
}
How do I a thread to upgrade, dynamically, a control on a form without making the form to be locked until the completion of another thread?
[Edit - Unchecked the "Treat my content as plain text, not as HTML" checkbox so the code blocks work]