简体   繁体   中英

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 ) eg Form1Object and then the button called the methods as so: Form1Object.Check1 and so on.

Although the thread still locked up (ie 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();
}      

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.

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM