在vb2008 / vb.net等待

时间:2011-08-21 12:28:49

标签: vb.net

我是VB6编码器,我正在转向VB8 / VB.NET

我知道如何在VB6中等待,但我的问题是我不知道如何在VB8 / VB.NET中等待。我有TextBox名为textbox2,其中包含我想要等待的秒数。我以前在VB6中使用wait 60,但当然VB2008是不同的。

任何人都可以帮我这样做吗?

6 个答案:

答案 0 :(得分:3)

我知道这是一个老问题,但我认为有太多相互矛盾的答案,我认为我使用的解决方案简单明了。 此外,当我从VB6切换到.net时,我写了这个,原因与OP相同。

Private Sub Wait(ByVal seconds As Long)
    Dim dtEndTime As DateTime = DateTime.Now.AddSeconds(seconds)
    While DateTime.Now < dtEndTime
        Application.DoEvents()
    End While
End Sub

答案 1 :(得分:0)

使用Thread.Sleep

Thread.Sleep(60000)

更新,发表评论:

要检索并转换文本框的值,请使用:

Dim sleepValue As Integer = Integer.Parse(textbox2.Text)

如果无法转换该值,则会抛出异常。

答案 2 :(得分:0)

[编辑:我重新阅读了该问题并看到它专门询问TextBox名为textbox2的问题,因此我更新了答案以反映这一点。]

嗯,我想一个答案就是使用:

System.Threading.Thread.Sleep(Int32.Parse(textbox2.Text) * 1000);

如果您的文本框包含等待的秒数。但是,如果您不在后台线程中,这将使您的应用程序挂起您等待的时间。

您还可以执行以下操作:

Dim StartTime As DateTime
StartTime = DateTime.Now

While (DateTime.Now - StartTime) < TimeSpan.FromSeconds(Int32.Parse(textbox2.Text))
    System.Threading.Thread.Sleep(500)
    Application.DoEvents()
End While

在等待时不会挂起UI。 (另外,您可以使用Convert.Int32(textbox2.Text)转换文本框中的数据。)

哦,在某些情况下,另一种可以避免UI锁定问题的方法是实现计时器回调。 (有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx。)为此,您

  • 在暂停之前执行您需要做的任何处理
  • 创建一个功能,从中断处理
  • 创建一个后来调用你的函数的计时器

代码:

Public Class MyClass

    Public MyTimer As System.Timers.Timer

    Public Sub OnWaitCompleted(source As Object, e As ElapsedEventArgs)
        MyTimer.Stop()
        MyTimer = Nothing
        DoSecondPartOfProcessing()
    End Sub

    Public Sub DoFirstPartOfProcessing()
        ' do what you need to do before the wait

        MyTimer = New System.Timers.Timer(Int32.Parse(textbox2.Text))
        AddHandler MyTimer.Elapsed, AddressOf OnWaitCompleted

        MyTimer.Start()
    End Sub

    Public Sub DoSecondPartOfProcessing()
        ' do what you need to do after the wait
    End Sub
End Class

答案 3 :(得分:0)

使用此功能,您的UI不会挂起。

For i = 1 to 300
 threading.thread.sleep(i * 1000)
 application.doevents
next

答案 4 :(得分:0)

尝试使用计时器

  Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    Dim interval As Integer = 0

    If Integer.TryParse(Me.TextBox2.Text, interval) Then
        Timer1.Enabled = True
        Timer1.Interval = interval
        Timer1.Start
    End If
End Sub

Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    'your code here
End Sub

在'计时器滴答的情况下,然后实现调用方法Timer.Stop()的逻辑,但这取决于你做什么。

问候。

答案 5 :(得分:-1)

我不知道您为什么要这样做以及为什么不使用线程,但这个sleep函数在vb6中的行为类似于wait

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    MsgBox("begin")
    Sleep(2000)
    MsgBox("end")
End Sub