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..
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.