Antarr Byrd
Antarr Byrd

Reputation: 26061

Is there an advantage to using a task here

I have a method that I am considering using a task to do some work. But is there really an advantage in this case? My reasoning was because the CheckInToWebDocs method is dependent on the presence of a file created by SaveDocument.

Without Task

 Private Sub PopulatePDF()
     Dim PrintLib As New Print
        Dim sPDFFilePath As String = ""
        If PrintLib.CreateEnrolledApp(EnrollmentID, sPDFFilePath) Then
           AppName = Page.ResolveUrl("~\SomeLocation\" & Path.GetFileName(sPDFFilePath))
           hlApplication.NavigateUrl = AppName

           SaveDocument(Constants.enumDocumentTypes.Application, EnrollmentID, Path.GetFileName(sPDFFilePath), sPDFFilePath)

           CheckInToWebDocs(EnrollmentID, sPDFFilePath)
        End If
    End Sub

Using Task

 Private Sub PopulatePDF()
        Dim PrintLib As New Print
        Dim sPDFFilePath As String = ""
        If PrintLib.CreateEnrolledApp(EnrollmentID, sPDFFilePath) Then
            AppName = Page.ResolveUrl("~\SomeLocation\" & Path.GetFileName(sPDFFilePath))
            hlApplication.NavigateUrl = AppName

            Dim saveDocumentTask As Task = Task.Run(Sub() SaveDocument(Constants.enumDocumentTypes.Application, EnrollmentID, Path.GetFileName(sPDFFilePath), sPDFFilePath))
            saveDocumentTask.Wait()

            CheckInToWebDocs(EnrollmentID, sPDFFilePath)
        End If
    End Sub

Upvotes: 0

Views: 47

Answers (1)

Marc L.
Marc L.

Reputation: 3399

Not the way you're using it. It will add the overhead of a parallel task, but you'll still be bound waiting on the task to complete.

Is there an Async variant of SaveDocument? If so, then you could make your own PopulatePDF() method Async, calling Await SaveDocumentAsync(...) (if naming follows convention). Then any consumer of PopulatePDF could also be Async, including responses to UI events which give you the benefit I think you're looking for.


Response to Comment: That's a shame. What I would say in this case: there is still no benefit to adding Task.Run to your implementation. This can be tempting, but you need to be aware that this spawns a new thread. That is, if you do something like this:

Private Async Function PreparePdfAsync() As Task
  ...
  Await Task.Run(Sub() SaveDocument(...))
  ...
End Function

you're only getting fake asynchronous code--synchronous code running on a background thread. In a UI scenario, your best option is to let the UI consumer call Task.Run() themselves if they need to, don't wrap that detail away, because the thread-spawning is non-obvious and potentially deleterious behavior.

See Stephen Cleary for more info on Task.Run etiquette and be sure to read up on his other intro articles if you're new to Async/Await.

Upvotes: 3

Related Questions