i am facing a trouble in my program. the program is a login checker, it reads a list of user & passwords then it test the login 1 by 1. the problem i am facing is when i put a long list the program take a while and so it needs a cancel button or pause. while the program running in that loop (login tests) the window form freezes and i cant press any buttons or even drug it around. here is the loop:
private void button1_Click(object sender, EventArgs e)
{
string spl = textBox5.Text;
int lin = textBox4.Lines.Count();
for (int i = 0; i < lin; i++)
{
string dick = textBox4.Lines[i];
Convert.ToString(dick);
string[] wordArray = dick.Split(':');
textBox1.Text = (Convert.ToString(wordArray[0]));
textBox2.Text = (Convert.ToString(wordArray[1]));
login();
}
}
Firstly I would like to tell you why you are faced with such a problem.
You are doing a 'heavy' operation in the main thread(UI thread), and while this thread is busy working with the task(checking for users and passwords), it will not response to the UI messages. That is, it will not check weather the message queue is empty or not, so it will do nothing with your clicking until the operation is over.
Secondly, I would like to find several ways to solve it.
Solution 1 Use a background thread to do the work
using System.Threading;
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() => {
this.Invoke(new Action(() => {
string spl = textBox5.Text;
int lin = textBox4.Lines.Count();
for (int i = 0; i < lin; i++) {
string dick = textBox4.Lines[i];
Convert.ToString(dick);
string[] wordArray = dick.Split(':');
textBox1.Text = (Convert.ToString(wordArray[0]));
textBox2.Text = (Convert.ToString(wordArray[1]));
login();
}
}));
});
thread.Start();
}
By this way, your UI with response to you when you are doing the operation.
Solution 2 Use a BackgroundWorker
It is similar to solution 1, just replace the user-created background thread with System.ComponentModel.BackgroundWorker, as for how to user a BackgroundWorker, please see https://msdn.microsoft.com/zh-cn/library/system.componentmodel.backgroundworker.aspx for more information.
Solution 3 Use ThreadPool
Use System.Threading.ThreadPool to create the background thread to work for you. In this way, you won't have to manage the thread by yourself. For more information, see https://msdn.microsoft.com/zh-cn/library/system.threading.threadpool(v=VS.80).aspx
Solution 4 Use a Task
Use System.Threading.Task to do your operation. see msdn:
https:// msdn.microsoft.com/zh-cn/library/system.threading.tasks.task.aspx
Attention: System.Threading.Task is availble from .NET Framework 4.0.
BTW, if you use the solution above, remember to use Form.Invoke() to access your control on the form, or set Control.CheckForIllegalCrossThreadCalls to false.