Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 349
  • Last Modified:

Main thread calling event from child thread without using Control.Invoke

Hi Experts,

I build an object with a method and an event.
In the method, I start a thread(child thread) and after a long process, the event is raised (from the child thread).

When I use this object in my form, I get an error which tells me to use Textbox.Invoke (which I understand and I know how to solve the error from my form). No problem.

The problem is I want the event to be raised in main thread, so no Textbox.Invoke error will be thrown in my form.

Thanks in advance for your help.
0
noulouk
Asked:
noulouk
  • 2
  • 2
1 Solution
 
WinterMuteUKCommented:
Hi noulouk,

I can't personally see anyway to force an event to fire on the main UI thread, the only thing you can really do in my opinion is to use the InvokeRequired check before doing anything on your UI.

Sorry!

Wint.
0
 
nouloukAuthor Commented:
Thanks Wint,

Main thread means the main thread of my object. No matter if this is main UI thread or a child of the main UI thread that instanciate my object.
Hope you see what I need and can help me more.

0
 
WinterMuteUKCommented:
The only way I can think of to get it back on the main thread is to actually raise the event from the main thread itself:

    internal class TestClass
    {
        public event EventHandler MyEvent;

        public void MyMethod()
        {
            Thread.CurrentThread.Name = "Main";
            Thread child = new Thread(new ThreadStart(ChildMethod));
            child.Start();

            child.Join(); //Will stop this running until child is finished.
            RaiseEvent( this, null ); //On main thread.
        }

        void RaiseEvent( object sender, EventArgs e )
        {
            Console.WriteLine("On thread: " + Thread.CurrentThread.Name);
            if ( MyEvent != null )
                MyEvent( sender, e );
        }

        private void ChildMethod()
        {
            Thread.CurrentThread.Name = "Child";
            Thread.Sleep(2000);
            RaiseEvent(this, null); //on child thread.
        }
    }

but it's not very nice, because it relies on the child only raising the event when it's finished - and obviously looses any point really of using a child thread at all!

Wint.
0
 
nouloukAuthor Commented:
This works, but this is very ugly as you tell.
Thanks anyway.

Regards.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now