Long Loop behind Button causing problems (newbie question)
I'm new at this so please bear with me. If the answer lies elsewhere then please redirect me. I could not find anything after a search.
I am using VS C# Express Beta 2, but I think my question is more general.
I have a small application which has all its activity behind one button. When clicked a lond search is started (loops). This causes problems with form refresh (solved with some flicker by putting a "this.Refresh();" in the inner loop) and causes the app to freeze when clich during a search.
How is this avoided? Does the answer invlove threading or is there comonly another approach?
Thanks in advance.
[685 byte] By [
abw2003] at [2007-12-16]
There are two ways to handle this, a easy way and a hard way.
An easy way is, rather than refreshing the form in the loop, simply change the Refresh() call to Application.DoEvents(). This tells the application to run any outstanding events, ie Paint, Move, Click events.
However be aware that this could allow the button to be clicked again, so you may want to check if you are already running the loop before running it.
The second way is threading. There are a number of different ways of doing this, however in .NET 2.0 there is a new component that handles the complexity of this. So have a look the the BackgroundWorker component.
Have a look at this post for an example on how it works (its in VB but the syntax is very similar):
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=9756