Okay, first off, this is not a thread for an answer like "Use delegates", or the like. I know how to use them, but one time I forgot to use them, and when going over my code, it worked, and I've been wondering why for a while.

http://screensnapr.com/e/xx68FK.jp[/img]

The image shows what I am saying. All the ones that have boxes around them, do not work. However, the ones that do not have boxes around them, do work.

I can honestly not come to a conclusion as to why this is at all. I am stumped.

Recommended Answers

All 2 Replies

I cannot see the image, and since you didnt write anything about the issue, we cannot help you out yet. So please...
But regarding your thread`s title, I can see you are trying to access to some control`s property, which you cannot directly.
Why not?
Because control is created on UI (main) thread, and since you run some code on a newly created thread, you cannot access control`s properties from it.
You already mentioned delegates, thats exactly what you need. So if you know how to use them, try it out.
In this is in no help, please upload the image ones again, or describe the issue a but better.
thx
bye

It is very hard for you, the developer, to know when a different thread is accessing a control at the same time as a another thread. Basically you can consider the collision occurences random, since there are too many determening factors to consider. Say, for example, your richtextbox control was being painted at the same time as you tried to access it's text field. The base class of the control's paint undoubtedly uses the text member to paint itself.

Unfortunately there is no clear answer here, especially not without more context of the entire application (where else are these control being referenced). Sometimes you can get away with thread violations, sometimes you can't. And sometimes it might seem like you can except for a very small set of circumstances where it can occur. Basically...like you said...continue using delegates.

Or simply do this:

public DoSomething(string data)
{
   if (this.InvokeRequired)
   {
       Invoke(DoSomething);
       return;
   }
   this.richtextbox.Text = data;
}

public StartThread()
{
   Thread t = new Thread(() => { DoSomething("Hello!"); }).Start();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.