我裏面的HttpHandler一個長期運行的進程,我異步執行使用異步等待.NET 4.5異步在4.5:取消和超時
這工作完全按預期...
我怎樣才能添加超時,以便在過程耗時過長時返回字符串'timeout'?
Protected Async Sub button1_Click(sender As Object, e As System.EventArgs)
Dim asyncHandler = New AsyncHandler
Await asyncHandler.ProcessRequestAsync(HttpContext.Current)
Response.Write(asyncHandler.Result)
End Sub
Public Class AsyncHandler
Inherits HttpTaskAsyncHandler
Public Property Result As String
Public Async Function ProcessRequestAsync(context As HttpContext) As Task
Me.Result = Await DoLongRunningProcessAsync(context)
End Function
Private Function DoLongRunningProcessAsync(context As HttpContext) As Task(Of String)
'TODO: add a timeout so that if this takes too long we return "timeout":
Return Task.Run(Of String)(Function() DoLongRunningProcess(context))
End Function
Private Function DoLongRunningProcess(context As HttpContext) As String
'perform long running process....
Return "success"
End Function
End Class
'CancellationTokenSource'可以採取一個時間跨度,構造函數的參數,這大大簡化了這種方法。 –
+1 @StephenCleary - 還有一個典型的'毫秒作爲int'超載可用 - http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource.cancellationtokensource.aspx –