Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected cross threading issue

I'm trying to do something very simple in principal, but I keep getting a cross-threading exception which has me stumped because I'm not setting out to use multiple threads.

I have a Windows Forms application. It launches another Windows Forms application (using the System.Diagnostics.Process class) , and catches the Exited event when that application is closed. My application event handler then tries to copy text from the clipboard to a control on the current displayed form. At this point a Cross-threading exception is thrown.

I assume that the problem is that the event from the closing application is in another thread (I'm outside my comfort zone here, so bear with me), so the question boils down to "How do I prevent this exception?"

I'm somewhat constrained into having to copy from the clipboard, but I could launch the other application a different way if that would solve the problem.

like image 457
haughtonomous Avatar asked Aug 05 '26 09:08

haughtonomous


1 Answers

The Exited event doesn't fire in the UI thread, it fires in some background thread created by the Process class to monitor the other process.

You need to marshal to the UI thread to access controls, this can be done by using the Control.Invoke method:

textbox1.Invoke(new Action(()=> textbox1.Text = Process.ExitCode.ToString()));
like image 55
Servy Avatar answered Aug 06 '26 23:08

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!