James Teare
James Teare

Reputation: 372

Main thread locking up in C#

I am faced with a problem. I am clicking a button that is calling several methods, although the main thread is locking up, so I created an instance of my class (which is Form1) e.g. Form1Object and then the button called the methods as so: Form1Object.Check1 and so on.

Although the thread still locked up (i.e. the GUI became unresponsive for a period) Is there anyway of getting around this, any examples would be greatly appreciated.

The code in question is below:

private void StartChecks_Click(object sender, EventArgs e)
{
    Form1 Form1Object = new Form1();
    Form1Object.InitChecks();
}

public void InitChecks()
{
    Check1();
    Check2();
    Check3();
    Check4();
    Check5();
    Check6();
    Check7();
}      

Upvotes: 2

Views: 1558

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273199

Creating a new Form does not start a new Thread.

You will have to move those CheckN() methods to a BackgroundWorker.

private void StartChecks_Click(object sender, EventArgs e)
{
  Form1 Form1Object = new Form1();
  var worker = new BackgroundWorker();
  worker.DoWork += (s, arg) => 
  {
     Form1Object.InitChecks();
  };

  // add progress, completed events

  worker.RunWorkerAsync();
}

But note that this require that the checks are independent and do not interact with any Control.

Upvotes: 4

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

You have several options here, and use them depending of your skill/preference/requirement:

  • if you don't update anything on the form while you process, start another thread and call everything on that thread, and update UI when appropriate (when everything is finished)
  • if you need to update things on your form while processing, you have several options:
    • either use Application.DoEvents() from the processing loop of every method you use
    • start a new thread then update form controls with Invoke() - if you try to update them directly, you'll be in trouble

If you care to comment and decide for one of the options, I can provide more info on just that...

Upvotes: 0

Tudor
Tudor

Reputation: 62439

What you need to do is start a parallel thread to do the check, so you won't lock up the main thread:

   private void StartChecks_Click(object sender, EventArgs e)
    {
        Form1 Form1Object = new Form1();
        Thread t = new Thread(
           o => 
           {
               Form1Object.InitChecks();
           });
        t.Start();
    }

Hopefully you don't need to actually retrieve anything from those calculations, so you can just fire and forget about it.

Upvotes: 3

Related Questions