如何选择性地运行在后台线程一些code? [英] How to optionally run some code on a background thread?

查看:163
本文介绍了如何选择性地运行在后台线程一些code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一个可配置的方式来运行在后台线程一些code和我不是太肯定的最佳做法会是什么。目前,我有沿着线的东西:

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?

更新:

这将从ASP.NET前端被称为(尽管别人可能),我使用的框架3.5。

This will be called from an ASP.NET front-end (although others are possible) and I am using Framework 3.5.

推荐答案

我会倾向于抽象在自己的类此行为远说TaskRunner,并且有它接受一个行动Run方法。这种分离线程问题,使您的code整洁,你也有你如何实现你的异步行为更大的灵活性,而无需此嵌入各种类应用程序中。

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.

如果你有一个Asp.Net应用程序运行的异步操作,你需要看一个机制来保持应用程序活着prevent应用例如回收通过查询你的网站,而动作页面运行保持活跃请求,以便运行时不会认为这是空闲的。

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.

这篇关于如何选择性地运行在后台线程一些code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆