Adress of thread
When I create a thread, I need to give it a method to be executed. Must this method be in a class? I would like to use a method in my main program (which is Form1). Is this possible?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jul 25, 2012, 12:00 AM EDT
Form1 is itself just a class (which inherits from Form) so, as long as the method is accessible from where-ever you're creating the thread, there's no reason why you can't use one of its methods for this purpose.
Per Jespersen23 reputationPosted Jul 25, 2012, 12:38 AM EDT
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
System.Threading.Thread MainThread;
MainThread = new Thread(Method);
MainThread.Start();
void Method()
{
TextBox1.Text = "Written in a thread";
}
}
}
VulpesRank #55 · 29.2K reputationPosted Jul 25, 2012, 12:52 AM EDT
Notice also that if you're accessing controls (such as textBox1) on a different thread to the one they were created on (the UI thread) then sometimes the code will work and sometimes it won't.
For it to always work, you need to marshal the code which accesses the control back to the UI thread. Here's how you could do it in this particular case :
Per Jespersen23 reputationPosted Jul 25, 2012, 1:08 AM EDT
Control.CheckForIllegalCrossThreadCalls = false;
Which I copied from an old VB program. It works and I hope it doen't give any greif later on, in which case, I'll try your suggestion.
thanks again!