我有这个卡住 UI 的函数:
Public Sub ValidateUrlContentAsync(externalApplyURL As String)
AsyncManager.OutstandingOperations.Increment()
Dim result = Threading.Tasks.Task.
Run( _
Async Function()
Return Await ValidateLinks.ValidateUrlContentAsync(externalApplyURL)
End Function).
ContinueWith(
Sub(t)
Try
If t.IsFaulted Then
Throw t.Exception
End If
If t.Result.Error IsNot Nothing Then
ErrorHandler.Log.Warn(
String.Format("ValidationError: {0}, Exception: {1}", externalApplyURL, t.Result.Error))
End If
AsyncManager.Parameters("validationResult") = t.Result.ResultValue.ToString()
Finally
AsyncManager.OutstandingOperations.Decrement()
End Try
End Sub)
End Sub
Public Function ValidateUrlContentCompleted(validationResult As String) As ActionResult
Return Json(validationResult, JsonRequestBehavior.AllowGet)
End Function
我认为 task.run
解决了这个问题,因为它创建了一个与 UI 线程分离的新线程,这段代码有什么问题?
最佳答案
对我来说突出的一件事是使用三个独立的异步代码模式(Await
、ContinueWith
和AsyncManager
)而不是仅仅使用Await
。
另一件主要的事情是您返回一个 ActionResult
- 表明这是一个 ASP.NET 应用程序 - 但谈论的是“UI 线程”。 ASP.NET 上没有 UI 线程。
因此,我将“卡住 UI”重新解释为“在处理程序完成之前不返回结果”,这正是 ASP.NET 的工作方式。
因此,首先删除所有不必要的 AsyncManager
、ContinueWith
和 Task.Run
代码,这确实简化了方法:
Public Function ValidateUrlContent(externalApplyURL As String) As Task(Of ActionResult)
Dim result = Await ValidateLinks.ValidateUrlContentAsync(externalApplyURL)
If result.Error IsNot Nothing Then
ErrorHandler.Log.Warn(String.Format("ValidationError: {0}, Exception: {1}", externalApplyURL, result.Error))
End If
Return Json(result.ResultValue.ToString(), JsonRequestBehavior.AllowGet)
End Function
接下来,解决“卡住 UI”问题。解决此问题的正确位置是在 UI 中,而不是在服务器 (ASP.NET) 端。防止UI卡住的方法是以异步方式调用服务器。如果您的 UI 是 .NET 应用程序,则可以将 Await
与 HttpClient
结合使用来异步调用它。
关于vb.net - 使用 Async-await 时 UI 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31364777/