How to handle/enforce single instance threading

I have a "worker" process that is running constantly on a dedicated server, sending emails, processing data extracts etc.

I want to have all of these processes running asynchronously, but I only want one instance of each process running at any one time. If a process is already running, I don't want to queue up running it again.

[example, simplified]

while (true)
{
    // SLEEP HERE

        Task task1 = Task.Factory.StartNew(() => DataScheduleWorker.Run());

        Task task2 = Task.Factory.StartNew(() => EmailQueueWorker.Run());
}

Basically, I want this entire process to run endlessly, with each of the tasks running parallel to each other, but only one instance of each task running at any point in time.

How can I achieve this in C# 5? What's the cleanest/best way to implement this?

EDIT

Would something as simple as this suffice, or would this be deemed bad?:

        Task dataScheduleTask = null;

        while (true)
        {
            Thread.Sleep(600);

            // Data schedule worker

            if (dataScheduleTask != null && dataScheduleTask.IsCompleted) dataScheduleTask = null;
            if (dataScheduleTask == null)
            {
                dataScheduleTask = Task.Factory.StartNew(() => DataScheduleWorker.Run());
            }
        }
Jon Skeet
people
quotationmark

This sounds like a perfect job for either an actors framework, or possibly TPL Dataflow. Fundamentally you've got one actor (or block) for each job, waiting for messages and processing them independently of the other actors. In either case, your goal should be to write as little of the thread handling and message passing code as possible - ideally none. This problem has already been largely solved; you just need to evaluate the available options and use the best one for your task. I would probably start with Dataflow, personally.

people

See more on this question at Stackoverflow