I could work, but makes little to no sense, but the following reason: you need to show the progress in your Fibonacci calculation, but you simply show then number of timer events. You are going to show nothing useful, isn't it obvious?
The solution is quite obvious: perform Fibonacci calculation in a separate thread. In this way, you always know at what iteration you are, so you can notify the progress bar accordingly. As Fibonacci algorithm is linear (Fibonacci sequence is itself defined in terms of algorithm), the number of iteration will also be proportional to time, that is, this is O(N)
time complexity.
Of course, as all UI operations, including progress bar update, should be done in your application's UI thread, also do it using
System.Windows.Forms.Control.Invoke
. Only you don't need to check
InvokeRequired
— it is
always required in this scenario. And main thing here it:
don't call Application.DoEvents
. Just don't.
Please see:
http://en.wikipedia.org/wiki/Big_O_notation[
^],
http://en.wikipedia.org/wiki/Time_complexity[
^],
http://en.wikipedia.org/wiki/Computational_complexity_theory[
^],
http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx[
^].
That's it.
Note that using a timer is generally a bad idea even when it is applicable. A thread is very typically better, as it's easy to represent some linear behavior. Also, timers inherently present problems with reliability. For example, did you ever tried to address the problem when a new timer event is invoked when the execution of a handler called by a previous event is still incomplete? The thread approach does not present such problems.
One little advice: from the very beginning, get rid of auto-generated names like "Form1", "Button1_Click", "progressBar1", etc. Not only they are ugly and irritating, they are not readable, does not give you the idea on what they do, semantically, and they even violate (good) Microsoft naming conventions: no numerals, no underscore. Rename all names using the refactoring engine of Visual Studio. Never use auto-generated names, use semantically sensible names.
—SA