Jump to content
Xtreme .Net Talk

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


Recommended Posts

Posted

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

  • Administrators
Posted

The basic problem is that you shouldn't update the UI from anything other than the UI thread, in .Net 2 this is enforced by default.

 

You will need to create a method in the form itself to perform the update and then .Invoke this from the background thread.

 

http://www.xtremedotnettalk.com/showthread.php?t=95412 is possibly worth a read.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...