Click here to Skip to main content
15,030,240 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am working on a slow form that takes some time to get open so I want to open a loading winform that I have designed.

I don't want to use Threading to achieve this.

This is not Working because the Loading form is not opening correctly till the code complete executing through all the code after LoadingWindow.Show()

What I have tried:

C#
//Whole code inside a Async method
LoadingWindow.Show();   //loading form
Thread.Sleep(5000);     //wait to simulate slowness
TestForm.Showdialog();  //Form
//then hide LoadingWindow and do other stuff
Posted
Updated 29-Jun-21 0:32am

Quote:
I don't want to use Threading to achieve this.

Well ... tough.

There is only one UI thread, and if you block it doing a long task, then the display doesn't get updated. Unless you move the long running code off the UI thread completely, nothing will get updated and it will not work the way you want it to.

And ... you do realize that threading is exactly what async await is all about?
   
Comments
thrainder 26-Jun-21 2:34am
   
See I used a Custom ShowDialog with async-await to achieve this and it kinda working and I'll let you know if it gets completed.
Richard Deeming 29-Jun-21 6:28am
   
"threading is exactly what async await is all about"

async/await is about making IO-bound code not block the current thread. It's only tangentially related to "threading". :)
You have on user interface thread.

Your problem cannot be solved by somehow waiting for the form to load.

You need to find out why the form is taking so long to load, and move that code out of the form load event, and into a background worker task.
   
Marking a method with the async keyword doesn't magically make it run asynchronously. It doesn't spin up any threads in the background. All it does is enable the use of the await keyword within that method, so that you can execute IO-bound code without blocking the current thread.

Calling Thread.Sleep from an async method will still block the current thread. Instead, call await Task.Delay(timeToWait);:
C#
LoadingWindow.Show();
await Task.Delay(5000); //wait to simulate slowness
TestForm.Showdialog();

But as honey said, this isn't going to solve your real problem. You need to find out why your form is taking so long to load, and change the loading logic so that it doesn't block the UI thread whilst it's loading.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900