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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T07:42:38+00:00 2026-06-06T07:42:38+00:00

I got a worker thread which throws events, which are handled by common handler

  • 0

I got a worker thread which throws events, which are handled by common handler methods, Actually i want to achieve that the handler methods are executed by the thread who created the object containing the worker thread which throws the events.

I tried following code:

public partial class Form1 : Form
{
    public event EventHandler Tested;

    public Form1()
    {
        InitializeComponent();

        Tested += new EventHandler(Form1_Tested);
    }

    private void Form1_Tested(object sender, EventArgs e)
    {
        Text = "Test";
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        #region Test 1
        // Works normal in GUI-Thread directly
        Form1_Tested(this, EventArgs.Empty);
        #endregion

        #region Test 2
        // Works in worker thread and throws GUI exception 
        // because of foreign thread access
        new Thread(new ThreadStart(delegate()
            {
                OnTested(EventArgs.Empty);
            })).Start();
        #endregion

        #region Test 3
        // Works in worker thread and returns to GUI-Thread
        // to throw the event, so no need in eventhandler 
        // to use Control.Invoke();
        AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);
        new Thread(new ThreadStart(delegate()
            {
                asyncOp.Post(new SendOrPostCallback(delegate(object obj)
                    {
                        OnTested(EventArgs.Empty);
                    }), null);
            })).Start();
        #endregion
    }

    protected virtual void OnTested(EventArgs e)
    {
        EventHandler tmpHandler = Tested;
        if (tmpHandler != null)
            tmpHandler(this, e);
    }
}

I took a cloeser look at the Thread I using

Thread.CurrentThread.ManagedThreadId;

Before starting the worker thread, the id of my main thread is “1”. Within the UI Thread, just right before fireing the event, the Thread ID (of the worker thread) is “4”.
Now taking a closer look at the Thread Id in the handler method the Thread Id is something like “10” – but instead I expected the ID to be “1”.
I’m very confused about that.

Generally: Is my snippet the right way to do it, or what’s the best practice doing this (or even a working example)?

I wanted to avoid using Invoke on the worker thread actually.

Regards,
Thomas

  • 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-06-06T07:42:41+00:00Added an answer on June 6, 2026 at 7:42 am

    Can you use a Task<> instead of a delegate? I think if you can, it might simplify things for you.

    Basically, if you create a Task<>, you can access the result of that task by accessing the .Result property which will wait for the thread to finish and then either give you the return code or – if the thread threw an exception – will rethrow that exception in the context of the thread that is accessing the .Result property.

    (If your thread doesn’t return anything, you can just call Task.Wait() instead of accessing .Result)

    Some code might help to explain what I mean:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var task = new Task<int>(() => test(1000, "Test1"));
                tryTask(task);
    
                task = new Task<int>(() => test(2000, "Test2"));
                tryTask(task);
    
                task = new Task<int>(() => test(1, "Test2"));
                tryTask(task);
            }
    
            static void tryTask(Task<int> task)
            {
                task.Start();
    
                try
                {
                    Console.WriteLine("Task result = " + task.Result);
                }
    
                catch (AggregateException ex)
                {
                    Console.WriteLine("Task threw an exception: " + ex.InnerException.Message);
                }
            }
    
            static int test(int value, string name)
            {
                Console.WriteLine("Starting thread " + name);
                Thread.Sleep(value);
                Console.WriteLine("Ending thread " + name);
    
                if (value == 1) // Magic number!
                {
                    throw new InvalidOperationException("Test Exception");
                }
    
                return value;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a worker thread that should wait for EDT to update the GUI
I got a thread that is just banishing.. i'd like to know who is
I've got a threaded invoke call that never returns. The thread runs just fine
I have got a C# user control, which has got it's own background worker
I've got a program that worked until recently. The offending code is shown here:
Got a programm with 2 threads. one thread is writing some stuff into the
I have a single thread producer which creates some task objects which are then
Is there a possibilty to make a thread that is only for showing a
I've got a List(Of IWorker) which contains a number of concretes. IWorker in turn
I'm in needed of a thread worker in my .NET application - .NET has

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.