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 1040747
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T15:15:44+00:00 2026-05-16T15:15:44+00:00

Why does this not work? What I am trying to do: I need a

  • 0

Why does this not work?

What I am trying to do:
I need a way to run specific methods in a specific thread that lives on till the end of the program.

My other possible options:
As I understand a possible way to do it would be to implement a queue. Into which I could push in methods I want to be run in the specific thread. In the specific thread, I would be spinning and sleeping / monitor.pulse to see if there are delegates waiting to be run in the queue.

My objective:
Is to avoid all the hardwork to create the delegate queue, maintain lock etc. It appears that a ready made solution exists in the WPF world called Dispatcher. WPF controls mostly inherit from DispatcherObject and somehow the whole thing works. What do I have to do to get this work?

using System;
using System.Threading;
using System.Windows.Threading;

namespace ThreadingTrials
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "mainThread";
            Engine engine = new Engine();
            Console.WriteLine("initializing SpecialEngine from {0}", Thread.CurrentThread.Name);
            engine.initialize();
            engine.doWork();
        }
    }
    class Engine:DispatcherObject
    {
        private EventWaitHandle InitializationComplete;
        private EventWaitHandle newWorkComplete;
        //private Dispatcher dispatcher;
        public Engine()
        {

        }
        public void initialize()
        {
            InitializationComplete = new EventWaitHandle(false, EventResetMode.ManualReset);
            Thread thread = new Thread(new ParameterizedThreadStart((hwnd)=>
            {
                InitializeSpecialEngineObject();
                while (true) ;
            }));
            thread.Name = "Special Engine Thread";

            thread.SetApartmentState(ApartmentState.STA);
            thread.Priority = ThreadPriority.Normal;
            thread.Start();
            Console.WriteLine("waiting for initialize at {0}", Thread.CurrentThread.Name);
            InitializationComplete.WaitOne();
        }
        private void InitializeSpecialEngineObject()
        {
            Console.WriteLine("doing initialization at {0}", Thread.CurrentThread.Name);
            Thread.Sleep(500);
            //dispatcher = Dispatcher.CurrentDispatcher;
            InitializationComplete.Set();
        }

        internal void doWork()
        {
            newWorkComplete = new EventWaitHandle(false, EventResetMode.AutoReset);
            //Dispatcher.Thread.Suspend();
            Dispatcher.Invoke((SendOrPostCallback)delegate
                {
                    Console.WriteLine("dispatched to {0}", Thread.CurrentThread.Name);
                    Thread.Sleep(500);
                    newWorkComplete.Set();
                },DispatcherPriority.Background, null);
            Dispatcher.Thread.Resume();
            Console.WriteLine("waiting for new work to complete at {0}", Thread.CurrentThread.Name);
            newWorkComplete.WaitOne();
        }
        private void doingWork()
        {
            Console.WriteLine("Doing work in {0}", Thread.CurrentThread.Name);

            Thread.Sleep(500);
        }
    }
}

Thanks for the input.
Fair enough. It was actually very little work to make a simple worker thread that waits for an event signifying a new task in queue of void() delegates, and runs them as they become available. I copied most of the code from a website online… Sorry lost reference. I had done it on that day, and should have edited this post earlier.

using System;
using System.Threading;
using System.Collections.Generic;

class ProducerConsumerQueue : IDisposable
{
    EventWaitHandle _wh = new AutoResetEvent(false);
    Thread _worker;
    readonly object _locker = new object();
    Queue<Action> _tasks = new Queue<Action>();

    public delegate void Action();

    public ProducerConsumerQueue()
    {
        _worker = new Thread(Work);
        _worker.Start();
    }

    public void EnqueueTask(Action work)
    {
        lock (_locker) _tasks.Enqueue(work);
        _wh.Set();
    }

    public void Dispose()
    {
        EnqueueTask(null);     // Signal the consumer to exit.
        _worker.Join();         // Wait for the consumer's thread to finish.
        _wh.Close();            // Release any OS resources.
    }

    void Work()
    {
        while (true)
        {
            Action task = null;
            lock (_locker)
                if (_tasks.Count > 0)
                {
                    task = _tasks.Dequeue();
                    if (task == null) return;
                }
            if (task != null)
            {
                task.Invoke();
            }
            else
                _wh.WaitOne();         // No more tasks - wait for a signal
        }
    }

}
class Program
{
    static void Main()
    {
        using (ProducerConsumerQueue q = new ProducerConsumerQueue())
        {
            q.EnqueueTask(delegate 
            {
                Console.WriteLine("Performing task: Hello");
                Thread.Sleep(1000);  // simulate work...
            });
            for (int i = 0; i < 10; i++) q.EnqueueTask(delegate 
            {
                Console.WriteLine("Performing task: "+ i);
                Thread.Sleep(1000);  // simulate work...
            });
            q.EnqueueTask(delegate 
            {
                Console.WriteLine("Performing task: Goodbye!");
                Thread.Sleep(1000);  // simulate work...
            });
        }

        // Exiting the using statement calls q's Dispose method, which
        // enqueues a null task and waits until the consumer finishes.
    }
}
  • 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-16T15:15:45+00:00Added an answer on May 16, 2026 at 3:15 pm

    You don’t call Dispatcher.Run. You’re assuming that a Dispatcher contains a Thread that does its work, but this is backwards. The first time that Dispatcher.CurrentDispatcher is called, a Dispatcher is created bound to the current thread. Note that even though your code doesn’t call CurrentDispatcher directly, it does do so indirectly by constructing a DispatcherObject (which captures CurrentDispatcher into a field).

    Review the WPF threading model docs, which contain all the details you need.

    If you want dispatcher-like functionality in a child thread but don’t want to take a dependency on WPF, you can use the ActionThread class from Nito.Async, which is roughly equivalent to a Dispatcher plus a dedicated Thread.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 523k
  • Answers 523k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Refer to this forum post. Basically, you need to go… May 16, 2026 at 9:37 pm
  • Editorial Team
    Editorial Team added an answer A message queue should be suited for this task. You… May 16, 2026 at 9:37 pm
  • Editorial Team
    Editorial Team added an answer select e.EmpID,e.EmpName,r.Sal,r.PaidYear from @emp e inner join @Remu r on… May 16, 2026 at 9:37 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I am trying to use the code in this article that lets you know
This is not a homework problem, though it is a work problem. Where months
Hey guys, I'm starting with Zend, and trying to understand the way it works
I need to load Dimensions from EDW Tables (which does maintain historical records) and
Edit: This makes alot more sense to me now that i've taken a step
This relates to a project to convert a 2-way ANOVA program in SAS to
I'm trying to write a function in Python that finds the first number in
I am currently trying to implement this into my current code: http://cubiq.org/iscroll I have
What I'm trying is this: 1) Create a new manged object 2) Get it's
I am trying to get JsTree to work to get a folder view in

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.