简单,无阻塞的睡眠方式?

Gul*_*har 9 vb.net sleep nonblocking

我用Google搜索并在这里阅读了一些线程,但我还没有找到一种简单的方法让VB.Net应用程序暂停一段时间并仍然保持应用程序响应:

Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Threading.Thread

[...]

''#How to keep screen frop freezing?
While True
  ListBox1.Items.Clear()

  ListBox1.Items.Add("blah")

  ''#Not much difference
  ListBox1.Refresh()

  ''#Wait 1mn
  Sleep(60000)
End While
Run Code Online (Sandbox Code Playgroud)

是否真的没有简单的非阻塞解决方案让VB.Net应用程序等待几秒钟?

谢谢.

小智 8

Public Sub ResponsiveSleep(ByRef iMilliSeconds As Integer)
    Dim i As Integer, iHalfSeconds As Integer = iMilliSeconds / 500
    For i = 1 To iHalfSeconds
        Threading.Thread.Sleep(500) : Application.DoEvents()
    Next i
End Sub
Run Code Online (Sandbox Code Playgroud)

调用ResponsiveSleep来暂停特定的代码片段,同时保持应用程序的响应性.为了使应用程序响应更快,iHalfSeconds可以修改为十分之一秒或百分之一秒

  • 我在使用`Application.DoEvents()`时遇到了问题.见[这里](https://social.msdn.microsoft.com/Forums/vstudio/en-US/48b4a763-7387-46da-8fc2-3e885670f62c/the-undo-operation-encountered-a-context-that-is - 例如,不同的论坛= netfxbcl). (2认同)

Set*_*ore 7

这是WinForms还是WPF?

如果它是WinForms,你可以使用计时器而不是while循环.然后你的应用程序仍然会响应并提升事件.

在WPF中,我认为你必须根据DispatchTimer类制作自己的计时器.


Gbo*_*han 5

Private Sub wait(ByVal interval As Integer)
    Dim stopW As New Stopwatch
    stopW.Start()
    Do While stopW.ElapsedMilliseconds < interval
        ' Allows your UI to remain responsive
        Application.DoEvents()
    Loop
    stopW.Stop()
End Sub
Run Code Online (Sandbox Code Playgroud)


小智 5

这段简单的代码怎么样 - :)

Private Async Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        MsgBox("This msgbox is shown immidiatly. click OK and hover mouse over other controls to see if UI is freezed")
        Await Task.Delay(5000)
        MsgBox("see? UI did'nt freez :). Notice the keyword 'Async' between Private and Sub")
    End Sub
Run Code Online (Sandbox Code Playgroud)

在声明的 sub 上使用Async,然后 putAwait Task.Delay(milliseconds)代替Thread.Sleep(milliseconds)