I am trying to know when a parallel.foreach is complete using tasks etc. I know this isn't easily possible as it runs on mulitple threads but I am sending emails using SendMailAsync and want to enable a button using MVVM property when the loop is complete.
Currently my code after the parallel for each is run before the loop is finished. With a standard foreach() it works as expected but I want to speed things up with parallel.foreach?
Does anybody know how I can do this?
HEre is my code:
Public Function SendEmail(email As String, bodystuff As String) As Task
Dim smtp As New SmtpClient("webmail.databarracks.com")
Dim from As New MailAddress("firstname.lastname@example.org", "Info", System.Text.Encoding.UTF8)
Dim [to] As New MailAddress(email)
Dim message As New MailMessage(from, [to])
message.Body = "The message I want to send is to this <b>contact: " & vbCrLf & bodystuff & "</b>"
message.IsBodyHtml = True
message.BodyEncoding = System.Text.Encoding.UTF8
message.Subject = "The subject of the email"
message.SubjectEncoding = System.Text.Encoding.UTF8
' Set the method that is called back when the send operation ends.
'AddHandler smtp.SendCompleted, AddressOf smtpClient_SendCompleted
Public Sub StartEmailRun()
Dim sWatch As New System.Diagnostics.Stopwatch()
Dim po As New ParallelOptions()
'Create a cancellation token so you can cancel the task.
_cancelToken = New CancellationTokenSource()
po.CancellationToken = _cancelToken.Token
'Manage the MaxDegreeOfParallelism instead of .NET Managing this. We dont need 500 threads spawning for this.
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount * 2
Dim v As Long = 0
Parallel.ForEach(contacts.Cast(Of Object), po,
Return SendEmail(row.Email.ToString, row.Name.ToString)
'Here I would like to update my property to True when the above loop is complete??
MyProperty = True
Timing = sWatch.ElapsedMilliseconds
Catch ex As Exception
P.S - C# code is welcome