功能优先于定时器



我是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:MMGRegbackup.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

我认为你在混淆概念。

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

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

  • 如何启动CMD流程?

  • 你的计时器从"1%"增长到"100%",时间间隔是多少+每1000毫秒1次?3000毫秒。。。进度条可以完成,并且CMD仍在运行。

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

从这个问题来看,您似乎使用了Run_Process,调用可能会阻塞,直到进程结束,因此您的UI线程无法对计时器事件采取行动。我认为你需要复习一下BackgroundWorker、Threadpool和点赞。

一般来说,您应该使用类似于以下伪代码的东西:

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

最新更新