0

I am trying to show a form with a spinner in the middle as a loading screen (not a progress indicator) while doing some long work and finally showing a form with the results, i am letting another thread handle the loading screen but when i use show() it just shows a black window (like its stuck) and sometimes it just flashes the window, while using ShowDialog() works perfectly but it blocks the thread and now i have to use Thread.Abort() and Thread.ResetAbort() to kill the thread, which i think you agree its not a good way to handle this. so my question is why ShowDialog() works but Show() doesn't.

I tried using async and await methods that i found here but it always comes back to ShowDialog(), what am i missing? and is there a safe way to exit the thread here?

public void button1_Click(object sender, EventArgs e)
{
    t1 = new Thread(() =>
    { 
        Loading l = new Loading();        
        l.Show(); //Doesn't work
        l.ShowDialog(); //Works but thread will be blocked  

        while (!ThreadExitFlag) 
        { 
        }

        l.Close();
    });
    t1.Start();
    LongWork(); //this will trigger the ThreadExitFlag by the end        
}
R Pelzer
  • 1,188
  • 14
  • 34
HMZ
  • 2,949
  • 1
  • 19
  • 30
  • 1
    You should not do UI operations outside the UI thread. Maybe [this](https://stackoverflow.com/questions/17271734/adding-panel-to-form-on-different-thread#17271794) will help you. – heap1 Jan 04 '19 at 11:59
  • To wit, flip things around and do `LongWork()` in a separate thread while you keep your UI in the main thread. – IceGlasses Jan 04 '19 at 13:18

1 Answers1

0

Finally, this worked for me, I am not sure if this is the right approach but it does the job perfectly. Code:

Thread  t1 = new Thread(() =>
            {
                Loading l = new Loading();

                Thread t2 = new Thread(() => {

                    while (!ThreadExitFlag)
                    {

                    }

                    l.Invoke(new Action(() => { l.Close(); }));

                });
                t2.Start();

                l.ShowDialog();


            });      
            t1.Start(); 


LongWork(); //this will trigger the ThreadExitFlag by the end 
HMZ
  • 2,949
  • 1
  • 19
  • 30