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

Started by
0 comments, last by paulecoyote 17 years, 7 months ago
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
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.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.

This topic is closed to new replies.

Advertisement