Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6018549
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T03:17:29+00:00 2026-05-23T03:17:29+00:00

I have a WPF app that from time to time needs to perform a

  • 0

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T03:17:29+00:00Added an answer on May 23, 2026 at 3:17 am

    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);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Context: I have a WPF App that uses certain unmanaged DLLs in the D:\WordAutomation\MyApp_Source\Executables\MyApp
This is an interesting conundrum. We have a WPF app that has a Vista-like
I have a Windows Forms app, that has a single ElementHost containing a WPF
I have a WPF App which is grinding to a halt after running out
Im running a console app that loads a dll and calls a method from
I have a WPF app which snaps to screen edges (I just set the
I'm creating a WPF app and have a system tray icon with a context
I have a mixed UI (Win App, WPF App, and soon an ASP.NET MVC
So, I have a WindowsFormsHost control in my WPF app (hosting a Dundas Chart)
I have a WPF (.Net 3.5 sp1) application that loads a bunch of data

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.