功能优先于定时器?

时间:2015-04-08 07:45:12

标签: vb.net timer

我是vb.net的新手并且想知道为什么我的函数(Run_Process)优先于计时器?

即使在功能之前设置了定时器,定时器(启动进度条)也会在函数调用后运行。

                Timer2.Start()
                ListBox1.Items.Add("Backing up the registry, Please wait as this may take some time...")
                ListBox1.ForeColor = Color.SlateBlue
                MsgBox(Run_Process("CMD.exe", "/C regedit.exe /e C:\MMG\Regbackup.Reg"))
                Timer2.Stop()
                ListBox1.Items.Clear()

该函数本身运行cmd命令。

计时器代码是

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick    
    ProgressBar1.Increment(1) 
    If ProgressBar1.Value = 100 And ListBox1.Items.Count() < 1 Then 
        Label1.Text = "Process complete with no obvious threats" 
        Button4.Enabled = False 
        Label1.ForeColor = Color.DarkGreen 
        Button1.Enabled = False 
    End If 
    Label3.Text = ProgressBar1.Value & (" %") 
End Sub

2 个答案:

答案 0 :(得分:1)

我认为你正在混合概念。

你启动计时器,我想它在启动Tick事件之前等待间隔期。同时,您启动了CMD。您在等待退出,还是在异步模式下运行? 然后,你停止计时器....你的进度条可能是10%或4%....

我的意思是:您的cmd进程和计时器无论如何都没有连接。

  • 如何启动CMD流程?

  • 你的计时器从&#34; 1%&#34;到了&#34; 100%&#34;,在什么时间间隔内?每1000毫升+1? 3000毫升? ...您的进度条可以完成,您的CMD仍在运行。

如果我是你,我会使用线程或更好的任务来执行此操作。但是,您可以考虑忘记您的计时器,并使用ProgressBar1.Style = Marquee&#34;而不是。

答案 1 :(得分:1)

看起来你使用this question中的Run_Process,Call可能会阻塞,直到进程结束,因此你的UI线程无法对timer事件采取行动。我想你需要了解BackgroundWorkerThreadpool并喜欢。

一般来说,你应该使用类似伪代码的东西:

Start a BackgroundWorker that
    Starts the Process
    Reads the Output
    Reports Progress (and ListBox Elements) via ReportProgress
Meanwhile your UI Thread
    Handles the BackgroundWorkers ProgressChanged Event
    Updates ListBox and ProgressBar
    Exits when BackgroundWorker is done