【问题标题】:Is it possible to await the calling task?是否可以等待调用任务?
【发布时间】:2019-07-22 05:57:28
【问题描述】:

有没有办法等待调用任务?

Async Function DoStuff() As Task
    StartDoingOtherStuff()

    ' Doing stuff
End Function

Async Function StartDoingOtherStuff() As Task
    ' Doing stuff

    Await callingTask

    ' Finish up
End Function

注意:我想使任务瘫痪,因为它涉及将文件上传到多个目的地。但我想等待调用任务,在所有上传完成后删除文件。

【问题讨论】:

  • 您只能等待您引用的任务
  • 我不能在调用对方时传递任务本身吗?
  • @VisualVincent 那是 C#。但是,是的,我想我明白了。这是不可能的。
  • 答案不包含任何代码,因此它适用于大多数支持 Async/Await 的 .NET 语言。尽管如此,C# 和 VB.NET 是如此平等,以至于您通常可以在它们之间进行转换。

标签: vb.net asynchronous async-await task


【解决方案1】:

根据 usr 对Get the current Task instance in an async method body 的回答,您可以这样做:

Private Async Function DoStuff() As Task
    'Capture the resulting task in a variable.
    Dim t As Task = (
        Async Function() As Task
            Console.WriteLine("DoStuff()")

            'First await. Required in order to return the task to 't'.
            Await Task.Delay(1)

            'Disable warnings:
            '    "Because this call is not awaited (...)"
            '    "Variable 't' is used before it has been assigned a value (...)"

#Disable Warning BC42358, BC42104

            'Call other method.
            DoOtherStuff(t)

#Enable Warning BC42358, BC42104

            'Simulate process.
            Await Task.Delay(3000)
        End Function
    ).Invoke()

    'Await if needed.
    Await t
End Function

Private Async Function DoOtherStuff(ByVal ParentTask As Task) As Task
    Console.WriteLine("DoOtherStuff()")

    'Await parent task.
    Await ParentTask

    Console.WriteLine("DoStuff() finished!")
End Function

通过使用 lambda 表达式,您可以捕获当前任务,然后将其传递给自身。 Await Task.Delay(1) 是必需的,以便异步方法返回其任务,以便可以将其设置为变量。但是,如果在调用 DoOtherStuff() 之前已经有另一个 await,则可以将其删除。

【讨论】:

  • Invoke() 是干什么用的?
  • @Fox : Invoke() 执行函数并返回其返回值(在本例中为Task)。基本上相当于做:FunctionName()。如果不调用它,您将只有一个指向函数的指针。
  • 我明白了。有用。但我认为将它包装在一个方法中是更简单的方法。感谢您的展示。
  • @Fox : 最适合你的 :)。这是为了如果你想避免在你的类中使用其他方法。
  • @Fox :如果您想缩短代码,可以省略 #Disable#Enable Warning。它们只是为了阻止编译器显示有关我们代码行为的警告(我们不需要,因为我们是故意这样做的)。
猜你喜欢
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2017-02-11
  • 2015-03-17
相关资源
最近更新 更多