如何在 vb.net 中执行一个又一个任务


    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

我应该放什么....

我认为

您错误地在某处转错了弯。如果您需要依次运行这四个语句,但不干扰循环,您需要做的就是创建一个执行多行/块 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

我只想在VisualVincent的答案中添加一些东西。我仍然更喜欢继续这样做

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 执行此操作,因为我非常好奇。

相关内容

  • 没有找到相关文章

最新更新