I have an application that, among other things, imports documents, then emails necessary parties to let them know that a document has been imported.

It turns out that determining whom to email, then performing the emailing, is what's taking the longest. I was thinking of doing something like this:

var document = ImportDocument();
ThreadPool.QueueUserWorkItem(s => SendEmail(document.Id));
return document;

... similar to DelayedJob in Rails, if that helps. Does that make sense in this context? What would you do?

  • Is there some reason why aren't you using a Task instead? How do you handle errors in sending the email? – svick Jun 26 '12 at 14:41
  • 2
    Not all of us are working in .NET 4. – Robert Harvey Jun 26 '12 at 15:42
  • How many emails are we talking about? What happened when you tried it? – Robert Harvey Jun 26 '12 at 16:24
  • @svick - Not really, I've never heard of Task. Would that be better suited to this? – Matt Grande Jun 26 '12 at 18:48
  • @RobertHarvey I haven't tried anything yet, this is more theoretical at this point. Let's say ~1000 documents per day, anywhere between 1 & 20 emails, depending on the document. – Matt Grande Jun 26 '12 at 18:49

Yes, this sounds like a reasonable enough approach.

At a broader level, this is related to work management.
You have a main task (import the document) and some related sub-tasks triggered by the main task (email notification, archiving, etc...).

Generally, the sub-tasks should be asynchronous to the main task as they don't really affect declaring the main task complete. IMO, if they do affect the main task being declared complete, then they would be part of the main task, not a sub-task.

You could also have a dedicated object that handles the email notifications. It would have a queue (or equivalent) to receive notification of the document being imported, and would start-up upon a notification event. If you end up with a notifications going out, consider this approach. It will avoid the churn of spinning up (and down) all of those threads and it will avoid overloading the system with secondary, async type tasks.

  • 2
    +1 for the queue idea. I actually wrote a Windows Service once that does this, and it works very well. – Robert Harvey Jun 27 '12 at 14:37
  • 1
    @RobertHarvey I struggled with where to draw the line for an introductory answer on work management. :-) Props for pointing out that once the asynch task handler becomes separated from the main flow, the options really open up with what can be done in placing that handler. – GlenH7 Jun 27 '12 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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