1.11M Members

Question that has been bugging me for a while; Access control properties from thread.

 
0
 

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.

 
0
 

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

 
0
 

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();
}
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: