我有一个 vs2010、4.0 vb.net、WinForms 应用程序在表单加载事件上调用 AttemptLogin。如果可能的话,我想避免阻止表单加载,我希望 4.0 中的任务和延续内容是正确的方法,因为我可以在默认调度程序上运行主要任务,并在 fromcurrentsynchronisationcontext 上继续运行,但是虽然我有OnAttemptLogin 工作我无法在继续调用我的 OnAttemptLoginCompleted 函数。
我认为这是因为 OnAttemptLogin 返回一个“RunToCompletion”任务,因此永远不会调用延续。但我不知道如何处理,我尝试了很多东西,但我现在很困惑自己,我几乎是在捣碎钥匙。任何人都可以提供任何建议吗?我只是做错了还是我的想法都错了?
到目前为止,这是我所拥有的, OnAttemptLogin 按我的预期工作,但它永远不会调用 LongRunning 任务继续。
请注意:我不能使用等待,因为我在 vs2010 .net4.0 中,所以我坚持使用 ContinueWith。
Public Sub AttemptLogin(OnAttemptLoginCompleted As Action(Of Task(Of HttpResponseMessage)))
Try
Dim LongRunningTask As Task(Of HttpResponseMessage) = Task.Factory.StartNew(Function()
Return OnAttemptLogin()
End Function, TaskScheduler.Default)
Dim UITask As Task(Of HttpResponseMessage) = LongRunningTask.ContinueWith(Sub(t)
OnAttemptLoginCompleted(t)
End Sub, TaskScheduler.FromCurrentSynchronizationContext)
LongRunningTask.Wait()
Catch ex As AggregateException
' nom nom nom
' do something useful
End Try
End Sub
Private Function OnAttemptLogin() As Task(Of HttpResponseMessage)
Dim aClient = New HttpClient()
Using (aClient)
' CREATE REQUEST
aClient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
aClient.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(String.Format("{0}:{1}", CallingDTO.Email, CallingDTO.Password))))
UserQueryDTO.UserName = UserDTO.Email
UserQueryDTO.Password = UserDTO.Password
Dim url As String = DnnRequest.GetUrl(Credentials.HttpAlias, cstModuleAssembly, "User", "CanLogin", False)
' POST REQUEST
Dim p As Task(Of HttpResponseMessage) = aClient.PostAsJsonAsync(url, UserQueryDTO).ContinueWith(Function(x)
' READ RESPONSE
Dim r = x.Result.Content.ReadAsAsync(Of HttpResponseMessage)()
r.Wait()
Return r.Result
End Function)
Try
p.Wait()
Catch ex As Exception
End Try
Return p
End Using
End Function