与任务并行库活动任务

2023-09-06 19:00:43 作者:天大地大姐妹最大

我使用的是.NET 4.0的任务并行库,用于执行长时间运行的任务。在长时间运行的任务有不同的阶段,在每个阶段,完成我要记录一些信息到一个文本文件或数据库。相反调用日志方法,在每一个阶段我想用即在每一个阶段有一些事件已经给开除了长期运行的任务和一些其他类有听这些事件,并从事件日志的相应信息的发布/订阅模式目的。

I'm using the .NET 4.0's Task Parallel Library for executing a long running task. The long running task has different stages and at each stage it completes I want to log some information to a text file or db. Instead of calling the log methods at every stage I thought of using a publisher/subscriber pattern i.e at every stage some event has to fired from the long running task and some other class has to listen to those events and log the appropriate information from the event object.

我不是很清楚在多线程环境中使用的事件。它是用在第三方物流活动是个好主意,我怎么能做到这一点?寻找一些建议。

I'm not very clear about using events in multi-threaded environment. Is it a good idea to use events in TPL and how I can do that? looking for some suggestions..

推荐答案

什么你描述的是什么的基于事件的异步模式。目前正由各个阶级BCL实施为好。例:WebClient类具有DownloadStringAsync方法(使用TPL或其他),它开始下载另一个线程与此类公开DownloadStringCompleted和DownloadProgressChanged(这正好映射到步骤正在你的长期运行的任务完成)

What you describing is exactly what "Event based Asynchronous" pattern is. Which is being implemented by various classes in BCL as well. Ex: WebClient class has DownloadStringAsync method which start the downloading on another thread (using TPL or whatever) and this class exposes DownloadStringCompleted and DownloadProgressChanged (which exactly maps to the steps being completed in your long running task).

所以,基本上这是罚款来实现这种模式。关键是要记住,这些事件将被提出在该任务运行,因此你需要确保这些事件的处理程序是知道这个事实的线程上。

So, basically this is fine to implement this pattern. The thing is to remember that these events will get raised on the thread on which the task was running hence you need to make sure that the handlers of these events are aware of this fact.