开发者

How to optionally run some code on a background thread?

I'm looking for a configurable way to run some code on a background thread and I'm not too sure what the "best practice" would be. Currently I have something along the lines of:

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

Is this a good way of implementing my requirement?

Update:

This will be called from an ASP.NET front-en开发者_StackOverflow社区d (although others are possible) and I am using Framework 3.5.


I would tend to abstract this behaviour away in its own class say TaskRunner, and have a Run method which accepts an Action. This separates threading concerns and makes your code neater, you also have more flexibility on how you implement your asynchronous behaviour without having this embedded in various classes in your application.

If you do have asynchronous actions running in a Asp.Net app, you will need to look at a mechanism to keep the application alive to prevent application recycling e.g. by polling a page in your site whilst the action is running to maintain active requests so the runtime doesn't think it's idle.


I suspect most people would tend to use the BackgroundWorker class instead. Of course you could also look at using Task(of T) in .NET 4.0 as well.


This is almost always a bad idea !!. For example, consider a case where you have the default settings in IIS. IIS shuts down the app pool, if it is idle (i.e. doesn't receive any requests) for 20 minutes. In such cases, if your background job runs for more than 20 minutes, it will fail. There are several other reasons for IIS to shut down the app pool. The app domain could recycle if someone changes web.config, thus causing failure of the job. Overall, it is not good for the stability of your web application.

The correct way to do this is using a windows services or some other scheduling component (may be a job in your database server). There are several open source options available. For e.g. Quartz.net

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜