在VB.net中延迟

Ree*_*ley 2 vb.net delay

我的问题是我需要在按下一个按钮后等待3-4秒才能检查它,这是我在button1_click下的代码:

        While Not File.Exists(LastCap)
            Application.DoEvents()
            MsgBox("testtestetstets")
        End While

        PictureBox1.Load(LastCap)
Run Code Online (Sandbox Code Playgroud)

我想我正在做一些非常简单的错误,我不是最好的VB,因为我只是学习所以任何解释都会很棒!

〜谢谢

小智 5

您可以使用(但不推荐):

Threading.Thread.Sleep(3000) 'ms
Run Code Online (Sandbox Code Playgroud)

这将等待 3 秒,但也会阻塞同一线程上的所有其他内容。如果您以表单运行此命令,则在等待结束之前,您的用户界面将不会响应。

顺便说一句:使用MessageBox.Show("My message")代替MsgBox(后者来自旧的 VB)。


Der*_*mes 5

如果你希望你的表单在3秒后继续运行,你可以改为添加一个Timer控件,使用如下代码:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    ' set the timer
    Timer1.Interval = 3000 'ms
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Timer1.Stop()
    'add delayed code here
    '...
    '...
    MessageBox.Show("Delayed message...")
End Sub
Run Code Online (Sandbox Code Playgroud)

将Timer控件从工具箱拖放到表单中.它在运行时不可见


Mar*_*all 5

如果你需要等待的原因是该文件使用创建的尝试FileSystemWatcher和响应的CreatedChanged活动方式,您正在响应的事件,而不是武断地等待时间的选择周期。

就像是:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    FileSystemWatcher1.Path = 'Your Path Here
    FileSystemWatcher1.EnableRaisingEvents = True
   'Do what you need to todo to initiate the file creation
End Sub

Private Sub FileSystemWatcher1_Created(sender As Object, e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created, FileSystemWatcher1.Changed
    If e.Name = LastCap Then
        If (System.IO.File.Exists(e.FullPath)) Then
            FileSystemWatcher1.EnableRaisingEvents = False
            PictureBox1.Load(e.FullPath)
        End If
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)


小智 5

或者更好的是使用秒表创建等待函数,这不会像线程睡眠一样停止同一线程中的进程

 ' Loops for a specificied period of time (milliseconds)
Private Sub wait(ByVal interval As Integer)
    Dim sw As New Stopwatch
    sw.Start()
    Do While sw.ElapsedMilliseconds < interval
        ' Allows UI to remain responsive
        Application.DoEvents()
    Loop
    sw.Stop()
End Sub
Run Code Online (Sandbox Code Playgroud)

用法

wait(3000)
Run Code Online (Sandbox Code Playgroud)

延迟 3 秒