4
votes

I have a WPF app that from time to time needs to perform a long-running operation - or rather, many small operations that in sum total take a while. I have found that the Task Parallel Library in .Net 4 works fine for this.

However, this operation by nature should run to completion before another of the same kind is started. And there is a very real chance that the user could perform an action that requires the process to run, even while the last one is still going. I would like to synchronize this so that only one is ever running at a time. When the running instance completes, another gains the locks and goes for it, etc. until there are no more of these to run.

I have a class that runs the process named EntityUpdater. In this class I thought it would be clever to define a syncronization object:

private static object _lockObject = new object();

Making it static should ensure that any EntityUpdater object will await its turn as long as the locking is correct, right?

So my naive first attempt did this before starting the Task (which in turns starts all the other little child tasks, attached to their parent):

Monitor.Enter(_lockObject, ref _lockAquired);

(_lockAquired is just a local bool)

The main task (the one with all the child tasks) has a continuation, which exists more or less only to do

Monitor.Exit(_lockObject);

I know I should put this in a finally, but it is pretty much the only code in the continuation, so I don't see how that would make a difference.

Anyway, I assume that there is some threading voodoo here that causes me to get the "Object synchronization method was called from an unsynchronized block of code" SynchronizationLockException. I have made sure that _lockAquired is actually true, and I have tried to Monitor.Enter in several different places, but I always get this.

So, basically, my question is how I can synchronize access to an object (the object itself is not important) so that only one copy of the process is running at any given time, and any others that may be started while one is already running will block? The complication - I guess - appears with the added demand that the lock should be released at some time in the future, when all the child tasks of the first TPL Task are complete.

UPDATE

Here is some code that shows what I am doing right now.

public class EntityUpdater
{
    #region Fields

    private static object _lockObject = new object();
    private bool _lockAquired;

    private Stopwatch stopWatch;

    #endregion

    public void RunProcess(IEnumerable<Action<IEntity>> process, IEnumerable<IEntity> entities)
    {
        stopWatch = new Stopwatch();

        var processList = process.ToList();

        Monitor.Enter(_lockObject, ref _lockAquired);

        //stopWatch.Start();

        var task = Task.Factory.StartNew(() => ProcessTask(processList, entities), TaskCreationOptions.LongRunning);
        task.ContinueWith(t =>
        {
            if(_lockAquired)
                Monitor.Exit(_lockObject);
            //stopWatch.Stop();

        });
    }

    private void ProcessTask(List<Action<IEntity>> process, IEnumerable<IEntity> entities)
    {

        foreach (var entity in entities)
        {
            var switcheroo = entity; // To avoid closure or whatever
            Task.Factory.StartNew(() => RunSingleEntityProcess(process, switcheroo), TaskCreationOptions.AttachedToParent);
        }
    }

    private void RunSingleEntityProcess(List<Action<IEntity>> process, IEntity entity)
    {
        foreach (var step in process)
        {
            step(entity);
        }
    }
}

As you can see, it is not complicated, and this is also probably far from production worthy - just an attempt that shows what I can't get to work.

The exception I get is of course in the Monitor.Exit() call in the task continuation.

I hope that makes this a bit clearer.

1
Sorry, but can you clearify a clearify a bit. It was certainly my impression that no two locked code blocks using the same object could execute simulteneously, so from what you write everything sounds correct. Perhaps some more code examples would help. - faester
Hi, sure, I will update with some more source code to show what I am doing. - Rune Jacobsen
The ContinueWith approach is not thread-safe, and unnecessarily complex. Consider a try/finally around a Parallel.ForEach(). - Henk Holterman
@Henk - Okey, I will try that - however, it was my understanding that the continuation in this case would run after all child tasks are done - and as long as it does little other than actually releasing the lock, could that cause a problem? My main concern is making this easy to call and non-blocking for the caller. Thanks! - Rune Jacobsen
Not a full answer, but be very careful about starting each Task by blocking on acquiring a lock. If you do this enough times, you can starve the thread pool and all sorts of bad things can happen (for instance, your continuations might not run, because they cannot be scheduled, because other tasks have started up and gone into a blocked state.) If you don't release until the continuation executes, you're now deadlocked. - Dan Bryant

1 Answers

3
votes

You could use a queue and ensure that only a single task is executing at a time which will process the queue, e.g.:

private readonly object _syncObj = new object();
private readonly ConcurrentQueue<Action> _tasks = new ConcurrentQueue<Action>();

public void QueueTask(Action task)
{
    _tasks.Enqueue(task);

    Task.Factory.StartNew(ProcessQueue);
}

private void ProcessQueue()
{
    while (_tasks.Count != 0 && Monitor.TryEnter(_syncObj))
    {
        try
        {
            Action action;

            while (_tasks.TryDequeue(out action))
            {
                action();
            }
        }
        finally
        {
            Monitor.Exit(_syncObj);
        }
    }
}