showing form in another thread
Hi,
I have a progress form that has a marguee progress bar.
I show that form before any lengthy process withing my application. The problem is that the form shows up but then the time consuming process takes over and the progress bar doesn't scroll.
How can I run that form in a different thread?
Thanks,
Re: showing form in another thread
Fire your lengthy process in it's own thread.
VB Code:
Dim t As New System.Threading.Thread(AddressOf LengthyProcess)
t.Start()
Re: showing form in another thread
The thing to do would be to open the form, then start the time-consuming operation in a separate thread from that form. You can define a class specifically for the thread, with the data it needs, a method to use as the entry point and a reference to the progress form. Make sure you use a delegate if you need to access the form or any of its controls from the other thread.
Re: showing form in another thread
Considering you're using a progress bar, you'll most probably need to update the progress bar's value at some point doing the long process. One of the golden rules of Windows programming is that you don't manipulate the UI thread from an external thread. VS 2005 is really good in this regard as it throws an exception if you attempt to break this rule, VS2002/2003 you had to use debug statements to get the thread ID and ensure they were processing correctly.
What I do in situations like this is create a worker class that holds a reference to the UI thread (You need this for thread switching), the alternative is to do the thread switching in the form's code, which can be messy, and then has to be implemented every time you use the class. I also use delegates for maximum control over things like parameters etc, but if you use the background worker class, most of this is fairly moot.
The trick is (IMO) to simply provide an Async method to call and use events to update the status of any progress monitoring things, it is in the raising of the event you implement your thread switching code. If done correctly, you can (relatively) easily create an object that can run both asynchronously and synchronously, with minimal effort on the implementing part to get it all working, both with thread switching and data retrieval.
BTW, if you use wild bill's method, you will not be able to report progress without a lot of mucking around for thread switching etc.
Re: showing form in another thread
This is where I learned the basics of multi-threading.
http://www.devx.com/DevX/10MinuteSol...20365/0/page/3
In your case, you want your worker thread to be able to change a control on your form's thread, so (as everyone else also said) you'll also need to add a Delegate to your form's class. The link I posted covers everything except the delegate aspect. I'm not sure why they left that out, as it is fairly important. But to me it is still a great beginner's tutorial.