Jump to content
  • Advertisement
Sign in to follow this  
Shaitan00

How to work around Cross-thread operation not valid with threading [C#/CS 2005]

This topic is 4445 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am creating a CHAT interface for my game (when networking, server/client style) and I ran into a little problem... The way it works... I have forms for the SERVER (frmServer) and CLIENTS (frmClient) each of them have a LISTBOX (lbChat) in which I input (lbChat.Items.Add(string)) text as the users type it - in essence a chatbox... So, let's use the CLIENT as an example (as it is simpler and the concept the same in both client and server cases)... The Client form (frmClient) creates a thread that is used to listen for chat messages (via TCP) - so what I did was pass the listbox itself (lbChat) to the thread thus (I thought) solving my problem of writing into the listbox when chat messages arrive (and are caught by the thread and not frmClient of course)... Now while debugging the code I get the following exception when my thread attempts to write in the listbox (lbChat) of frmClient General Exception: System.InvalidOperationException: Cross-thread operation not valid: Control 'lbChat' accessed from a thread other than the thread it was created on. So now the question is how do I work around this cross-thread exception? How do I pass information (chat text) from my listener threads (and there will be multiple of them in the field, one per client) to the centralized listbox (lbChat) on the form? I need some kind of method to transfer information while also reducing the chances of running into contention issues (do I need to use ReaderWriterLock?), thing is I have no clue how to accomplish this task (I thought simply passing in the listbox would allow me to write to it in each of the threads)... Any ideas, hints, and help would be greatly appreciated, thanks

Share this post


Link to post
Share on other sites
Advertisement
There are actually a couple of ways around this. A easier way in C#2 then in C#1.

What's interesting is how many C++ developers fall in to this same trap, but don't have an exception thrown to tell them that it's actually not on to directly change controls from another thread!

You used to have to do lots of Invokes, but you can now use a far friendlier BackgroundWorker for threads that update Forms.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!