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

  • Home
  • SEARCH
  • 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 6158081
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T20:53:43+00:00 2026-05-23T20:53:43+00:00

I’m using an invocation described in this question: Synchronization accross threads / atomic checks?

  • 0

I’m using an invocation described in this question: Synchronization accross threads / atomic checks?

I need to create an method invoker that any thread can call, which will execute on the main executing thread at a specific given point in its execution.

I ended up using this implementation of the Invoker class:
I am aware that is might not be the most efficient in terms of locking, but it’s theoretically working in a similar enough way than Thread.MemoryBarrier(), such as the one SLaks suggested.

EDIT: With MRAB’s suggestions.

public class Invoker
{
    private Queue<Action> Actions { get; set; }

    public Invoker()
    {
        this.Actions = new Queue<Action>();
    }

    public void Execute()
    {
        Console.WriteLine("Executing {0} actions on thread {1}", this.Actions.Count, Thread.CurrentThread.ManagedThreadId);

        while (this.Actions.Count > 0)
        {
            Action action;

            lock (this.Actions)
            {
                action = this.Actions.Dequeue();
            }

            action();
        }

        Console.WriteLine("Executed, {0} actions left", this.Actions.Count);
    }

    public void Invoke(Action action, bool block = true)
    {
        if (block)
        {
            Console.WriteLine("Invoking");
            SemaphoreSlim semaphore = new SemaphoreSlim(0, 1);

            lock (this.Actions)
            {
                this.Actions.Enqueue(delegate
                {
                    try
                    {
                        action();
                        Console.WriteLine("Actioned");
                    }
                    catch
                    {
                        Console.WriteLine("Exception thrown by action");
                        throw;
                    }
                    finally
                    {
                        semaphore.Release();
                        Console.WriteLine("Released");
                    }
                });
            }

            Console.WriteLine("Enqueued");

            Console.WriteLine("Waiting on thread {0}", Thread.CurrentThread.ManagedThreadId);
            semaphore.Wait();
            Console.WriteLine("Waited");
            semaphore.Dispose();
        }
        else
        {
            this.Actions.Enqueue(action);
        }
    }
}

The many Console.WriteLine are there to help me track my freezing, which happens regardless of whether or not this logging is present (i.e., they are not responsible of the freezing and can be discarded as culprits).

The freezing occurs in a scenario where:

  1. An execution thread runs in a loop (calling Invoker.Execute).
  2. On 2 other threads, 2 methods are invoked relatively simultaneously (calling Invoker.Invoke).
  3. The first method works and gets invoked fine, but the second one freezes after “Waiting”, that is, after semaphore.Wait().

Example output:

Executing 0 actions on thread 1
Executed, 0 actions left
Executing 0 actions on thread 1
Executed, 0 actions left
Invoking
Enqueued
Waiting on thread 7
Executing 1 actions on thread 1
Actioned
Released
Executed, 0 actions left
Waited
Invoking
Enqueued
Waiting on thread 8

What I suspect to be happening is that the execution thread somehow blocks, hence not executing the second enqueued action, and not releasing the semaphore (semaphore.Release()), and thus not allowing the execution to proceed.

But that is extremely weird (in my opinion), since the execution is on another thread than the semaphore blocking, and so it shouldn’t block, right?

I’ve tried to build a test case that reproduces the problem out of the context environment, but I can’t get it to reproduce. I post it here as an illustration of the 3 steps I explained earlier.

static class Earth
{
    public const bool IsRound = true;
}

class Program
{
    static Invoker Invoker = new Invoker();

    static int i;

    static void TestInvokingThread()
    {
        Invoker.Invoke(delegate { Thread.Sleep(300); }); // Simulate some work
    }

    static void TestExecutingThread()
    {
        while (Earth.IsRound)
        {
            Thread.Sleep(100); // Simulate some work

            Invoker.Execute();

            Thread.Sleep(100); // Simulate some work
        }
    }

    static void Main(string[] args)
    {
        new Thread(TestExecutingThread).Start();

        Random random = new Random();

        Thread.Sleep(random.Next(3000)); // Enter at a random point

        new Thread(TestInvokingThread).Start();
        new Thread(TestInvokingThread).Start();
    }
}

Output (as supposed to occur):

Executing 0 actions on thread 12
Executed, 0 actions left
Executing 0 actions on thread 12
Executed, 0 actions left
Invoking
Enqueued
Waiting on thread 13
Invoking
Enqueued
Waiting on thread 14
Executing 2 actions on thread 12
Actioned
Released
Waited
Actioned
Released
Waited
Executed, 0 actions left
Executing 0 actions on thread 12
Executed, 0 actions left
Executing 0 actions on thread 12

The actual question: What I’m asking, at this point, is if any experienced threading programmer can see a logical mistake in the Invoker class that could ever make it block, as I see no possible way of that happening. Similarly, if you can illustrate a test case that makes it block, I can probably find where mine went wrong. I don’t know how to isolate the problem.

Note: I’m quite sure this is not really regarded as a quality question for its specificity, but I’m mostly posting as a desperate cry for help, as this is hobby programming and I have no coworker to ask. After a day of trial and error, I still can’t fix it.

Important update: I just had this bug occur on the first invocation too, not necessarily only on the second. Therefore, it can really freeze by itself in the invoker. But how? Where?

  • 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-23T20:53:43+00:00Added an answer on May 23, 2026 at 8:53 pm

    I think you should lock on Actions when enqueuing and dequeuing. I occasionally had a null-reference exception here:

    this.Actions.Dequeue()();
    

    probably because a race condition.

    I also think that the enqueued code should not dispose of the semphore, but just leave that to the enqueuing thread:

            Console.WriteLine("Invoking");
            SemaphoreSlim semaphore = new SemaphoreSlim(0, 1);
    
            this.Actions.Enqueue(delegate
            {
                action();
                Console.WriteLine("Actioned");
                semaphore.Release();
                Console.WriteLine("Released");
            });
    
            Console.WriteLine("Enqueued");
    
            Console.WriteLine("Waiting");
            semaphore.Wait();
            Console.WriteLine("Waited");
            semaphore.Dispose();
    

    again because of race conditions.

    EDIT: It has occurred to me that if the action throws an exception for some reason, the semaphore won’t be released, so:

                    this.Actions.Enqueue(delegate
                    {
                        try
                        {
                            action();
                            Console.WriteLine("Actioned");
                        }
                        catch
                        {
                            Console.WriteLine("Exception thrown by action");
                            throw;
                        }
                        finally
                        {
                            semaphore.Release();
                            Console.WriteLine("Released");
                        }
                    });
    

    Could that be the problem?

    EDIT: Are you locking this.Actions when modifying it?

    When dequeuing:

                Action action;
                lock (this.Actions)
                {
                    action = this.Actions.Dequeue();
                }
                action();
    

    and enqueuing:

                lock (this.Actions)
                {
                    this.Actions.Enqueue(delegate
                    {
                        ...
                    });
                }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Does anyone know how can I replace this 2 symbol below from the string
I'm making a simple page using Google Maps API 3. My first. One marker
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have some data like this: 1 2 3 4 5 9 2 6
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

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.