Newbie: Thread question

  • Thread starter Thread starter Craig Lister
  • Start date Start date
C

Craig Lister

I am trying to write an app that accepts many connection from a client
(TCP).

So, threads are required (I assume).

I have created a thread, but when a connection is established, I'd like to
write this to a RichEdit. So the code inside the thread code needs to access
this RichEdit control. Problem is, many threads can access it at the same
time, so it gives error...

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

How do I allow a thread to write to a control on my form?

Thanks,
Craig




Websites:
http://www.thelisters.co.uk/
http://www.myschoolmates.com/
 
Check Control.Invoke and Control.BeginInvoke in MSDN, if you are running
v2.0 you should have to look at the BackGroundWorker class.

Willy.
 
Craig Lister said:
I am trying to write an app that accepts many connection from a client
(TCP).

So, threads are required (I assume).

I have created a thread, but when a connection is established, I'd like to
write this to a RichEdit. So the code inside the thread code needs to access
this RichEdit control. Problem is, many threads can access it at the same
time, so it gives error...

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

How do I allow a thread to write to a control on my form?

See http://www.pobox.com/~skeet/csharp/threads/winforms.shtml
 
Hi,
Two things can help here I guess.
1) the code that writes to the text box should be inside a "lock" scope.
2) You cant access windows controls from threads other then the one they are
owned by which is the one that they were created on. So you have to take
help of "asychronous" calls by calling BeginInvoke (which is a thread safe
method) on the control.

Few posts back I answered a question "Notifying the user of the current
action" (10/4/2005). That code can help.

Ab.
http://joehacker.blogspot.com
 
While the threads are separated from the main thread, they have access to
the main thread's class instance context. However, this is not exactly
threadsafe, but they can raise events that the main thread can respond to.
In addition the main thread can raise events that the child threads can
respond to.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
 

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

Back
Top