Posts

Showing posts with the label thread

Form.Show() From Another THread - C#.Net

Today I ran into a mojor headache. I have a main form that instantiates a secondary form from its constructor. I also register to a receive data event that I have based on a socket. Because the socket uses threading, when my event delegate is called, it is being called from the context of another thread. It is inside the execution of the delegate that I ran into trouble. When I receive data from the socket, I want to open the secondary form and do something with it. Immediately I know that I am going to have to use Invoke on the secondary form in order to safely modify it from the other thread. My original attempt looked like this (I will use an inline delegate here to simplify this listing): void dataReceived() { If(secondaryForm.InvokeRequired) { MethodInvoker myDelegate = delegate { secondaryForm.Show(); //do other work on secondaryForm }; secondaryForm.Invoke(myDelegate)...