I have a main that start a thread for my form. I want to update the label1 text from the main thread. I have created my delegate and my method to update it  but i don't know how to access the form thread and to modify the label1 text.  Here my code for the main:   public class Program {     /// &lt;summary&gt;     /// The main entry point for the application.     /// &lt;/summary&gt;      [STAThread]     static void Main()     {         //Thread l'affichage de la form         Program SecondThread = new Program();         Thread th = new Thread(new ThreadStart(SecondThread.ThreadForm));         th.Start();            //Update the label1 text      }      public void ThreadForm()     {         Application.EnableVisualStyles();         Application.SetCompatibleTextRenderingDefault(false);         Application.Run(new Form1());      }  }   Here the code for my form1:    public partial class Form1 : Form {      public delegate void SetTextLabelDelegate(string text);      public void SetTexLabel(string text)     {         if (this.label1.InvokeRequired)         {             SetTextLabelDelegate SetLabel = new SetTextLabelDelegate(SetTexLabel);             this.Invoke(SetLabel, new object[] { text });         }         else         {             this.label1.Text = text;             this.Refresh();         }            }      public Form1()     {         InitializeComponent();     } }   How can i access to the form thread and to modify the label1 text ? I am using C# and .Net 4.5.
122495
I cannot figure out how to make a C# Windows Form application write to a textbox from a thread.  For example in the Program.cs we have the standard main() that draws the form:  static void Main() {     Application.EnableVisualStyles();     Application.SetCompatibleTextRenderingDefault(false);     Application.Run(new Form1()); }   Then we have in the Form1.cs:  public Form1() {     InitializeComponent();      new Thread(SampleFunction).Start(); }  public static void SampleFunction() {     while(true)         WindowsFormsApplication1.Form1.ActiveForm.Text += "hi. "; }   Am I going about this completely wrong?  UPDATE  Here is the working code sample provided from bendewey:  public partial class Form1 : Form {     public Form1()     {         InitializeComponent();         new Thread(SampleFunction).Start();     }      public void AppendTextBox(string value)     {         if (InvokeRequired)         {             this.Invoke(new Action&lt;string&gt;(AppendTextBox), new object[] {value});             return;         }         textBox1.Text += value;     }      void SampleFunction()     {         // Gets executed on a seperate thread and          // doesn't block the UI while sleeping         for(int i = 0; i&lt;5; i++)         {             AppendTextBox("hi.  ");             Thread.Sleep(1000);         }     } }
4696
What are the differences between delegates and an events? Don't both hold references to functions that can be executed?
105996
When I'm debugging, I often have to deal with methods that does not use an intermediate variable to store the return value :     private int myMethod_1()    {       return 12;    }     private int myMethod_2()    {       return someCall( someValue );    }   Well, in order to recreate a bug, I often have to change values on the fly. Here, I could want to see what happens when myMethode_1 return zero. Same thing for myMethod_2.  Is there a way to do that without modifying the code ? What I would like to do, it's to place a breakpoint on the return line (or on the closing bracket) and type-in a new return value.  Note : I'm using Visual Studio 2005 and Visual Studio 2008.  Thank !
9326
How do I pass a value from a child back to the parent form? I have a string that I would like to pass back to the parent.  I launched the child using:  FormOptions formOptions = new FormOptions(); formOptions.ShowDialog();
49572
What is the maximum number of threads you can create in a C# application?  And what happens when you reach this limit?  Is an exception of some kind thrown?
100125
The following method does not compile. Visual Studio warns "An out parameter may not be used within an anonymous method". The WithReaderLock(Proc action) method takes a delegate void Proc().  public Boolean TryGetValue(TKey key, out TValue value) {     Boolean got = false;     WithReaderLock(delegate     {         got = dictionary.TryGetValue(key, out value);     });     return got; }   What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).
36187
When would you call Java's thread.run() instead of thread.start()?
61917
I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable).  As each phase of the startup goes, I want to update the splash screen with progress.  I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the main() method?). I am also missing how Application.Run() works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway?  I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all :)
42034
First off, this is a question about a desktop application using Windows Forms, not an  question.  I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...  otherForm.Controls["nameOfControl"].Visible = false;   It doesn't work the way I would expect. I end up with an exception thrown from Main. However, if I make the controls public instead of private, I can then access them directly, as so...  otherForm.nameOfControl.Visible = false;   But is that the best way to do it? Is making the controls public on the other form considered "best practice"? Is there a "better" way to access controls on another form?  Further Explanation:  This is actually a sort of follow-up to another question I asked, . The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.  Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)
80656
I want do something like this:  Button btn1 = new Button(); btn1.Click += new EventHandler(btn1_Click); Button btn2 = new Button(); // Take whatever event got assigned to btn1 and assign it to btn2. btn2.Click += btn1.Click; // The compiler says no...   Where btn1_Click is already defined in the class:  void btn1_Click(object sender, EventArgs e) {     // }   This won't compile, of course ("The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -="). Is there a way to take the event handler from one control and assign it to another at runtime? If that's not possible, is duplicating the event handler and assigning it to another control at runtime doable?  A couple of points: I have googled the heck out of this one for awhile and found no way of doing it yet. Most of the attempted approaches involve reflection, so if you read my question and think the answer is incredibly obvious, please try to compile the code in Visual Studio first. Or if the answer really is incredibly obvious, please feel free to slap me with it. Thanks, I'm really looking forward to seeing if this is possible.  I know I could just do this:  btn2.Click += new EventHandler(btn1_Click);   That's not what I'm looking for here.  This is also not what I'm looking for:  EventHandler handy = new EventHandler(btn1_Click); Button btn1 = new Button(); btn1.Click += handy; Button btn2 = new Button(); btn2.Click += handy;
4525
To be specific, I was trying this code:  package hello;  public class Hello {      Clock clock = new Clock();      public static void main(String args[]) {         clock.sayTime();     } }   But it gave the error      Cannot access non-static field in static method main   So I changed the declaration of clock to this:  static Clock clock = new Clock();   And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
30039
When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods.
749
I have a scenario. (Windows Forms, C#, .NET)   There is a main form which hosts some user control. The user control does some heavy data operation, such that if I directly call the UserControl_Load method the UI become nonresponsive for the duration for load method execution. To overcome this I load data on different thread (trying to change existing code as little as I can)   I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.   Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.    The pseudocode would look like this:  CODE 1  UserContrl1_LoadDataMethod() {     if (textbox1.text == "MyName") // This gives exception     {         //Load data corresponding to "MyName".         //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage.     } }   The Exception it gave was     Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.   To know more about this I did some googling and a suggestion came up like using the following code  CODE 2  UserContrl1_LoadDataMethod() {     if (InvokeRequired) // Line #1     {         this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));         return;     }      if (textbox1.text == "MyName") // Now it wont give an exception     {     //Load data correspondin to "MyName"         //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage     } }   BUT BUT BUT... it seems I'm back to square one. The Application again  become nonresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.  I don't know whether I perceived this right or wrong. I'm new to threading.  How do I resolve this and also what is the effect of execution of Line#1 if block?  The situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.   So only accessing the value so that the corresponding data can be fetched from the database.
118792
The following code  using System.Threading;  class Test {     volatile int counter = 0;     public void Increment()     {         Interlocked.Increment(ref counter);     } }   Raises the following compiler warning:  "A reference to a volatile field will not be treated as volatile"   Am I doing something wrong here to raise this warning? Why does the compiler me warn about this?
112570
Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It's kind of cumbersome and I'm wondering if there is a more straightforward approach.
91216
Our project is running on Windows CE 6.0 and is written in C++ . We have some problems with the code , and we are unable to debug . We also found out that if in our application we create threads and try to printf from them , the output won't appear . The only output that will appear is the one from the main thread . I would like to do the following :   create a custom windows message use as it's WPARAM the address of a char* I want to show on the screen use as it's LPARAM the length of the char* I want to show on the screen send the message process it when it comes , so that it prints the char*   How could I create the custom windows message ? What are the types of WPARAM and LPARAM ? Is it possible to do what I just wrote ?  Thanks
84126
I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class  public class UserInfo {     [Category("change me!")]     public int Age     {         get;         set;     }     [Category("change me!")]     public string Name     {         get;         set;     } }   This is a class that is provided by a third party vendor and I can't change the code. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.  May I know how to do this?