0
    For Each account In _accounts11
        Dim newtask = account.readbalancesAsync()
        newtask = newtask.ContinueWith(Sub() account.LogFinishTask("Getting Balances", starttime))
        newtask = newtask.ContinueWith(Async Function() account.getOrdersAsync())
        newtask = newtask.ContinueWith(Sub() account.LogFinishTask("Getting Orders", starttime))

        tasklist.Add(newtask)
    Next


    Await Task.WhenAll(tasklist.ToArray)
    Dim b = 1

基本上,对于每个帐户,我想做 account.readbalancesAsync 之后,我想做 account.getOrdersAsync()

我留下代码newtask.ContinueWith(Sub() account.LogFinishTask("Getting Balances", starttime))以表明我知道 ContinueWith 是如何工作的。但是,在那之后,我需要继续执行另一项任务。

我该怎么做?

我想做的是这样的

    For Each account In _accounts11
        await account.readbalancesAsync()
        account.LogFinishTask("Getting Balances", starttime)
        await account.getOrdersAsync())
        account.LogFinishTask("Getting Orders", starttime)

        tasklist.Add(newtask)
    Next

显然,如果我这样做,那么一个帐户必须等待另一个帐户完成。我希望所有帐户并行运行。

或者让我们看看这段代码

dim response1 = await client.GetAsync("http://example.com/");
dim response2 = await client.GetAsync("http://stackoverflow.com/");

说我这样做

dim newtask = client.GetAsync("http://example.com/").continueWith(....)
await newtask

我应该放什么......

4

2 回答 2

3

我认为你在某个地方错误地转错了方向。如果您需要一个接一个地运行这四个语句,但又不干扰循环,您需要做的就是创建一个执行多行/块 lambda 表达式的任务。

例如:

For Each account In _accounts11
    Dim newtask = Task.Run( 'Start a new task.
        Async Function() 'Multiline lambda expression.
            Await account.readbalancesAsync()
            account.LogFinishTask("Getting Balances", starttime)
            Await account.getOrdersAsync()
            account.LogFinishTask("Getting Orders", starttime)
        End Function
    ) 'End of Task.Run()

    tasklist.Add(newtask)
Next
于 2019-04-29T20:29:52.740 回答
1

我只想在 VisualVincent 的回答中添加一些内容。我还是更喜欢用 continueWith 来做这个

Private Async Function readBalancesAndOrderForEachAccount(starttime As Long) As Task
    Await readbalancesAsync()
    LogFinishTask("Getting Balances", starttime)
    Await getOrdersAsync()
    LogFinishTask("Getting Orders", starttime)
End Function

Public Shared Async Function getMarketDetailFromAllExchangesAsync2() As Task
    Dim CurrentMethod = MethodBase.GetCurrentMethod().Name
    Dim tasklist = New List(Of Task)
    Dim starttime = jsonHelper.currentTimeStamp

...

        For Each account In _accounts11
            Dim newtask = account.readBalancesAndOrderForEachAccount(starttime)
            tasklist.Add(newtask)
        Next
        Await Task.WhenAll(tasklist.ToArray)
        Dim b = 1
   ...
    End Function

这似乎工作。但是,我想了解如何使用 continueWith 执行此操作,因为我很好奇。

于 2019-04-29T20:45:37.480 回答