用VB2005构建反应灵敏的应用程序
添加时间: 2006-2-13 8:43:36 作者: VB教程 阅读次数:118 来源: http://www.d9soft.com
| 前言 Visual Basic .NET中最突出的特色之一就是构造多线程应用程序。但由于多线程应用程序天然的复杂性及挑战性,使许多VB开发人员没有充分利用这一新提供的功能。 在了解Visual Basic 2005创建多线程应用程序是多么容易以前,让我们看一看通常程序开发人员所遇到的挑战:长时间运行的任务在执行过程中经常限制了用户的输入或使用户无法与操作系统进行交互。 一、长时间运行的任务实例 在这个实例中,我们将对一个规定的整数计算斐波纳契数列(每个数等与数列前两个数之和)。也许这个例子对开发人员开发应用程序来说用处不大,但它的确是一个非常合适的例子,它不需要开发人员具备数据库或是其他一些必须得知识。你想象的应用程序中的长时间运行的任务类型可能是耗时的数据库操作、遗传系统调用、外部服务调用或是其他的一些深层次的资源操作。 为了创建这个项目,首先创建一个窗体应用程序,它带有一个进度条、两个按钮、一个数字输入框和一个显示结果的标签。两个按钮分别命名为startSyncButton 和cancelSyncButton,将标签的text属性设置为no result。对窗体上的各个控件进行仔细布局调整以后,界面效果如下: ![]()
Private Sub startSyncButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles startSyncButton.Click ’ Reset the text in the result label. result.Text = [String].Empty ’ Disable the UpDown control until ’ the synchronous operation is done. Me.numericUpDown1.Enabled = False ’ Disable the Start button until ’ the synchronous operation is done. Me.startSyncButton.Enabled = False ’ Enable the Cancel button while ’ the synchronous operation runs. Me.cancelSyncButton.Enabled = True ’ Get the value from the UpDown control and store it ’ in the globle variable numberToCompute. numberToCompute = CInt(numericUpDown1.Value) ’ Reset the variable for percentage tracking. highestPercentageReached = 0 ’ Start the synchronous operation. result.Text = ComputeFibonacci(numberToCompute).ToString ’ Enable the UpDown control. Me.numericUpDown1.Enabled = True ’ Enable the Start button. startSyncButton.Enabled = True ’ Disable the Cancel button. cancelSyncButton.Enabled = False End Sub 正如其他应用程序一样,这里没有什么特别之处,当用户点击开始按钮后,程序开始计算并将结果现在是屏幕上,但是,这个程序有一个非常明显的错误。 当按下按钮后,主线程既要对来自于用户界面的操做进行反应,又要忙于计算斐波纳契数列值。如果你开始这个应用程序并输入一个大的数字,例如50,你将看到你的应用程序将给用户带来的窘境。点击Start按钮后,试着将应用程序最小化或移动程序窗口,这时应用程序将没有任何反应或反应非常迟钝。 ![]()
![]()
|
上一篇文章: 探索VB系列中的事件处理的奥秘 下一篇文章: Visual Basic编程常见问题及解答




