1
\$\begingroup\$

Is this a good method to optionally run some code on a background thread depending on a configuration setting? This will primarily be called from an ASP.NET front-end (although others are possible) under Framework 3.5. I'm attempting to keep this as DRY as possible.

Dim sendEmails = Sub() 
                     Dim emailToSend As New SendEmailRequest() 
                     TransferCommonValuesTo(emailToSend, request, sendingUser) 
                     usersToSendEmailTo.ForEach(Sub(u) 
                                                    TransferValuesTo(emailToSend, u, m_EmailMessageMerger.GetMergedMessage(request.Message, u)) 
                                                    m_EmailSender.Send(emailToSend) 
                                                End Sub) 
                 End Sub 


If cfg.SendBulkEmailUsingBackgroundThread Then 
    Dim worker As New Thread(sendEmails) 
    worker.IsBackground = True 
    worker.Start() 
Else 
    sendEmails() 
End If
\$\endgroup\$
1
  • 3
    \$\begingroup\$ In a nutshell.. yes. This is basically spot on, any style points aside, the only other thing I can think is frequently in the context of IIS people tend to use the threadpool instead of their own threads, but the threadpool doesn't have a guaranteed start time which is plausibly necessary for your instance. There may be some style mishaps in there but I have thoroughly forgotten my old VB chops so I couldn't speak to them. \$\endgroup\$ Aug 28, 2011 at 17:03

1 Answer 1

2
\$\begingroup\$

Maybe.

Depends, as always, what happens if you get multiple threads running.

So you start this thread going, your code will move on, and if you start this again, and it hasn't finished the previous round of sending emails. What happens?

If its all thread safe, then no problem, but it might send some emails out of order. If its not thread safe, then hilarity ( or calamity ) ensues :-)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.