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

时间:2019-04-29 19:23:56

标签: vb.net task continuewith

    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

我应该在...里放什么。

2 个答案:

答案 0 :(得分:3)

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

例如:

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

答案 1 :(得分:0)

我只想在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做到这一点。