gpt4 book ai didi

.net - Task.Wait()不包含任何链接的(ContinueWith)任务

转载 作者:行者123 更新时间:2023-12-03 13:15:06 24 4
gpt4 key购买 nike

如果你有

Private Shared Sub msg(Optional message As String = "")
Debug.WriteLine(Threading.Thread.CurrentThread.ManagedThreadId & " " & message)
End Sub
<TestMethod()>
Public Sub TestMethod1()
Dim cancel As New Threading.CancellationTokenSource
msg("starting")
Dim start As DateTime = DateTime.Now
Dim task As New Task(Sub()
msg("in thread")
Do Until Now.Subtract(start).TotalMilliseconds > 2000
Threading.Thread.Sleep(500)
msg("loop")
cancel.Token.ThrowIfCancellationRequested()
Loop
End Sub, cancel.Token, TaskCreationOptions.LongRunning)
task.ContinueWith(Sub(result As task)
msg("Continue task running")
Debug.WriteLine(result.Status.ToString & If(result.Exception Is Nothing, ", no exception", ", exception occurred " & result.Exception.GetType.Name))
Do Until Now.Subtract(start).TotalMilliseconds > 10000
cancel.Token.ThrowIfCancellationRequested()
Threading.Thread.Sleep(500)
msg("innerloop")
Loop
End Sub)
task.Start()
Try
If Not task.Wait(4000, cancel.Token) Then
msg("wait expired, time to cancel)")
cancel.Cancel()
End If
task.Wait()

Catch ex As OperationCanceledException
msg("task was cancelled")
Finally
msg("finishing")
End Try
End Sub

问题是当我执行task.Wait(4000,cancel.Token)时,这将最终失败,因为ContinueWith任务不会在超时内完成。

似乎“等待”仅适用于任务,并且没有考虑链,我如何才能等待“链”完成?

最佳答案

等待ContinueWith函数返回的任务。

关于.net - Task.Wait()不包含任何链接的(ContinueWith)任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8305617/

24 4 0
文章推荐: multithreading - 当我们已经有了多线程时,多处理有什么好处?
文章推荐: .net - 多线程资源争用
文章推荐: c# - 关于在 Thread 中传递的局部变量
文章推荐: multithreading - Guava ListenableFuture 如何等待来自堆栈的信息?