我想获得一个简单的异步例子与等待工作,但我不认为它是。我认为这个代码应该需要10秒(或者超过10秒)才能运行,因为每个循环中的每个函数都应该异步运行。简单的ASP.NET 4.5异步并在VB.NET中等待
这是一个asp.net web表单,Async =“true”出现在页面声明中。
Inherits System.Web.UI.Page
Protected Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This needs to execute different asynchronous processes based on the array value
Dim ItemList(2) As String
ItemList(0) = "A"
ItemList(1) = "B"
ItemList(2) = "C"
Dim time_start As DateTime
Dim time_end As DateTime
Dim r1 As String
Dim r2 As String
Dim r3 As String
'capture start time
time_start = DateTime.Now
'run async processes for each item in array
For Each element As String In ItemList
Select Case element
Case "A"
r1 = Await processAsyncA(10) & " "
Case "B"
r2 = Await processAsyncB(10) & " "
Case "C"
r3 = Await processAsyncC(10) & " "
End Select
Next
'capture end time
time_end = DateTime.Now
'display total duration in seconds
Label1.Text = DateDiff(DateInterval.Second, time_start, time_end)
End Sub
Protected Async Function processAsyncA(ByVal waittime As Integer) As Task(Of String)
Await Task.Delay(waittime * 1000)
Return waittime.ToString
End Function
Protected Async Function processAsyncB(ByVal waittime As Integer) As Task(Of String)
Await Task.Delay(waittime * 1000)
Return waittime.ToString
End Function
Protected Async Function processAsyncC(ByVal waittime As Integer) As Task(Of String)
Await Task.Delay(waittime * 1000)
Return waittime.ToString
End Function
在此先感谢!
我有VB.NET和Task.delay问题;我几乎重复了上面的代码。但是当我运行代码时,浏览器就锁定了。就像线程继续运行一样,永远不会释放回调用线程(UI)。注意:Thread.sleep可以工作,但它使我的代码同步运行。我正在寻找并行运行。 Task.Dely的任何帮助确实锁定了我的概念验证(在上面的例子中),我们将非常感激。我甚至尝试使用下面的[答案];浏览器停止工作(锁定)。 – 2013-04-29 20:44:17