I\'m writting a Windows Forms application in C# that executes a lot of long-running procedures on a single button click. This make the GUI to freeze till the execution. Also
As Baboon said one way to go is Background worker approach another way if you are using .Net 4 or above could be to use Task class
Task class simplifies the execution of code on background and UI thread as needed. Using Task class you can avoid writing extra code of setting events and callbacks by using Task Continuation
Reed Copsey, Jr. has a very good series on Parallelism on .Net also take a look at it
for example a synchronous way of doing things can be
//bad way to send emails to all people in list, that will freeze your UI
foreach (String to in toList)
{
bool hasSent = SendMail(from, "password", to, SubjectTextBox.Text, BodyTextBox.Text);
if (hasSent)
{
OutPutTextBox.appendText("Sent to: " + to);
}
else
{
OutPutTextBox.appendText("Failed to: " + to);
}
}
//good way using Task class which won't freeze your UI
string subject = SubjectTextBox.Text;
string body = BodyTextBox.Text;
var ui = TaskScheduler.FromCurrentSynchronizationContext();
List mails = new List();
foreach (string to in toList)
{
string target = to;
var t = Task.Factory.StartNew(() => SendMail(from, "password", target, subject, body))
.ContinueWith(task =>
{
if (task.Result)
{
OutPutTextBox.appendText("Sent to: " + to);
}
else
{
OutPutTextBox.appendText("Failed to: " + to);
}
}, ui);
}