如何返回Threading.Task(Of Boolean)的值

时间:2013-12-10 14:47:31

标签: .net vb.net multithreading asynchronous task

我想在方法中运行一个任务并返回Task生成的值,我该怎么做?

这就是我正在尝试的:

Private function blahblahblah as boolean

    Return Threading.Tasks.Task.Factory.StartNew(Of Boolean)(
        Function() As Boolean
            For X As Integer = 0 To RetryInterval
                NetworkAvaliable(String.Format(NoWebsiteRetryMessage, RetryInterval - X), True, StatusControl)
            Next
            Return False
        End Function)

End Function

重要的是澄清我想要在不创建方法之外的其他变量的情况下这样做,例如:

dim value as boolean

Private function blahblahblah as boolean

    Threading.Tasks.Task.Factory.StartNew(Of Boolean)(
        Function() As Boolean
            For X As Integer = 0 To RetryInterval
                NetworkAvaliable(String.Format(NoWebsiteRetryMessage, RetryInterval - X), True, StatusControl)
            Next
            value = False
        End Function)

     Return value

End Function

我想避免这样的事情。

1 个答案:

答案 0 :(得分:3)

使用Async / Await

Private Async Sub callBlahBlahBlah()
    Dim result = Await blahblahblah()
End Sub

Private Function blahblahblah() As Task(Of Boolean)
    Return Threading.Tasks.Task.Factory.StartNew(Of Boolean)(
        Function() As Boolean
            For X As Integer = 0 To RetryInterval
                NetworkAvaliable(String.Format(NoWebsiteRetryMessage, RetryInterval - X), True, StatusControl)
            Next
            Return False
        End Function)
End Function