简体   繁体   中英

Synchronizing with an object while using the Task Parallel Library

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.

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

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM