Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 529
  • Last Modified:

Thread exception on timer event

So from my main form, I instantiate a class that I wrote, that has a public DebugCode event.  From my form, I call a function that starts a timer object, part of the class.  When the timer elapsed event is called, it triggers my DebugCode event, which sends a value as a parameter.  In my form's handler for this event, I try to put this value in a textbox.  When I try to set the textbox text property, I get the following exception...

"Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on."

What the heck??  I looked at the associated help file and there is about three pages of sample code on the "right", "threadsafe" way to do this, and a property CheckForIllegalCrossThreadCalls  that you can set to false.  What's the deal with this, will I get in trouble if I suppress this check??   Are you really not supposed to do this very simple thing anymore?  (If not, I might end up putting this on my "how they've broken VB with .NET" list.)


1 Solution
Mike TomlinsonMiddle School Assistant TeacherCommented:
Hi riceman0,

They haven't broken anything...   =)

You just haven't experienced this type of thing before because VB6 was not multithreaded.  All languages in the .Net family deal with this issue and the correct way to handle is NOT to set the CheckForIllegalCrossThreadCalls  property to false.

The System.Timers.Timer and System.Threading.Timer runs in their own thread while the System.Windows.Forms.Timer does NOT run in its own thread.

To properly update a GUI control from a seperate thread you need to use a Delegate and the Invoke() method.

See here for a simple example of a Delegate:

Here is an example of running a thread in a Class and making that class raise events that are handled on the main UI:

Read those links and then ask any questions you might have...
riceman0Author Commented:


Esp. for the clarification that this is specific to non-form-based timers; that helps me not hold this against VB.NET.  :)


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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