How to close the form?

S

snow

Hi all,

I open Form2 and add a handler in the form load event: AddHandler
SerialPort1.DataReceived, Addressof ComPort_DataReceived. In
ComPort_DataReceived procedure, I try to close Form2 and open another
form Form3 after data received, I got run time error "Cross thread
operation not valid". How to solve this problem?

Thanks for the help!
 
S

Stanimir Stoyanov

You are receiving the exception because the ComPort is raising the event
from another thread and you are trying to close Form2 (which is created by
another one).

Replace your call to Me.Close with Me.Invoke(New Action (AddressOf
Me.Close)).

You can read more about the multithreading model if you are interested.
 
S

Stanimir Stoyanov

P.S. The Action delegate is only available in .NET 3.5 and later so you have
to define if yourself if compiling against an older version of the
framework.

Private Delegate Sub Action();
....
Me.Invoke(New Action (AddressOf Me.Close)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top