I want to use thread and close my form after some operations.But I get a cross thread error .solutions?       new System.Threading.Thread(s =&gt;         {               Close;   }).Start();
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.
46363
What is the proper way to terminate a Swing application from the code, and what are the pitfalls?  I'd tried to close my application automatically after a timer fires. But just calling dispose() on the JFrame didn't do the trick - the window vanished but the application did not terminate. However when closing the window with the close button, the application does terminate. What should I do?
81176
The following is okay: try {     Console.WriteLine(&quot;Before&quot;);      yield return 1;      Console.WriteLine(&quot;After&quot;); } finally {     Console.WriteLine(&quot;Done&quot;); }  The finally block runs when the whole thing has finished executing (IEnumerator&lt;T&gt; supports IDisposable to provide a way to ensure this even when the enumeration is abandoned before it finishes). But this is not okay: try {     Console.WriteLine(&quot;Before&quot;);      yield return 1;  // error CS1626: Cannot yield a value in the body of a try block with a catch clause      Console.WriteLine(&quot;After&quot;); } catch (Exception e) {     Console.WriteLine(e.Message); }  Suppose (for the sake of argument) that an exception is thrown by one or other of the WriteLine calls inside the try block. What's the problem with continuing the execution in catch block? Of course, the yield return part is (currently) unable to throw anything, but why should that stop us from having an enclosing try/catch to deal with exceptions thrown before or after a yield return? Update: There's an  - seems that they already have enough problems implementing the try/finally behaviour correctly! EDIT: The MSDN page on this error is: .  It doesn't explain why, though.
37422
I'm getting this error every few days. I won't see the error for a few days then I'll get a flurry of 20 or so all with in a minute or so.  I've been very thorough going throw my code so that I'm using this basic setup for my DB access.  try {   myConnection.Open();   mySqlDataAdapter.Fill(myDataTable);   myConnection.Close(); } Catch (Exception err) {   if (myConnection.State != ConnectionState.Closed) myConnection.Close();   throw err; }   The way I understand it this should execute my queries and immediately release the connection back to the pool but if something goes wrong with the query then I catch the excpetion close my connection then throw the error up, which eventually gets trapped at the application level and logs and emails me the error.  Even using this throughout my code I'm still running across the issue. What can I do to diagnose the root cause of the issue?
77898
What's the best way to shut down the computer from a C# program?  I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
17111
Just wondering what the difference between BeginInvoke() and Invoke() are?   Mainly what each one would be used for.  EDIT: What is the difference between creating a threading object and calling invoke on that and just calling BeginInvoke() on a delegate? or are they the same thing?
97673
Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:  tasksForm.Visible = false; tasksForm.Show();   Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.  When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:  tasksForm.WindowState = FormWindowState.Minimized; tasksForm.Show();   I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.
109795
I have a form with a lot of controls on it.  How can I detect when the mouse leaves the form?  I've tried wiring up a MouseLeave event for every single control and the form, but that does not work because those events fire all the time as the mouse passes over controls.  Is there a way that actually works.?
101443
Does anyone have any advice for a consistent way to unit test a multithreaded application?  I have done one application where our mock "worker threads" had a thread.sleep with a time that was specified by a public member variable.  We would use this so we could set how long a particular thread would take to complete its work, then we could do our assertions.  Any ideas of a better way to do this?  Any good mock frameworks for .Net that can handle this?
3914
I am writing a server, and I send each action of into a separate thread when the request is received. I do this because almost every request makes a database query. I am using a threadpool library to cut down on construction/destruction of threads. My question is: what is a good cutoff point for I/O threads like these? I know it would just be a rough estimate, but are we talking hundreds? Thousands? How would I go about figuring out what this cutoff would be?  EDIT: Thank you all for your responses, it seems like I am just going to have to test it to find out my thread count ceiling. The question is though: how do I know I've hit that ceiling? What exactly should I measure?
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.
87780
I have a legacy WinForms Mdi App in VB.Net 2.0 which I am adding functionality to. One of the additions is a warning which needs to be raised when the current time nears a specified value (a deadline). My intention is to check the time once an hour until there is less than an hour until the deadline, then display warnings at specified intervals until the time's up.  The user needs to be able to continue to use the app up to and even after the deadline, but they need to periodically be made aware of the deadline's proximity.   The app does not use System.Threading yet and my knowledge of it is limited at this time. I do know that there are 3 different Timer() methods available:    System.Threading.Timer(), Windows.Forms.Timer() and  System.Timers.Timer()   My question is, which is the best way to go with this? I attempted to use the threaded timer, but since WinForms are not thread safe I got a run time error trying to access another class. Is it worth making the class/form thread safe? Am I completely off track?  Thanks.
110919
In a windows form application what is the impact of calling Thread.Sleep(1) as illustrated in the following code:  public Constructor() {     Thread thread = new Thread(Task);     thread.IsBackground = true;     thread.Start(); }  private void Task() {     while (true)     {         // do something         Thread.Sleep(1);     } }   Will this thread hog all of the available CPU?    What profiling techniques can I use to measure this Thread's CPU usage ( other than task manager )?
110516
I am trying to perform two operations. First I want to increase the size of a GameObject and then delay for 0.1s before returning it back to its original size. However, when I try using StartCoroutine(), it keeps giving me the error :  An object reference is required to access not-static members   even though I made my Delay() function static. Can somebody please tell me what I'm doing wrong?  public static void MoveSelected(int choice) {     GameObject rock1 = GameObject.Find("Rock1");     GameObject paper1 = GameObject.Find("Paper1");     GameObject scissors1 = GameObject.Find("Scissors1");      Vector3 scl;      if (choice == 1)     {         scl = rock1.transform.localScale;         scl.x *= 1.1f;         scl.y *= 1.1f;         rock1.transform.localScale = scl;          StartCoroutine(Delay());          scl.x /= 1.1f;         scl.y /= 1.1f;         rock1.transform.localScale = scl;     }     else if (choice == 2)     {         scl = paper1.transform.localScale;         scl.x *= 1.1f;         scl.y *= 1.1f;         paper1.transform.localScale = scl;          StartCoroutine(Delay());          scl.x /= 1.1f;         scl.y /= 1.1f;         rock1.transform.localScale = scl;     }     else if (choice == 3)     {         scl = scissors1.transform.localScale;         scl.x *= 1.1f;         scl.y *= 1.1f;         scissors1.transform.localScale = scl;          StartCoroutine(Delay());          scl.x /= 1.1f;         scl.y /= 1.1f;         rock1.transform.localScale = scl;     }  }  static IEnumerator Delay() {     yield return new WaitForSeconds(0.1f); }
120245
What's a better way to start a thread, _beginthread, _beginthreadx or CreateThread?  I'm trying to determine what are the advantages/disadvantages of _beginthread, _beginthreadex and CreateThread.  All of these functions return a thread handle to a newly created thread, I already know that CreateThread provides a little extra information when an error occurs (it can be checked by calling GetLastError)... but what are some things I should consider when I'm using these functions?  I'm working with a windows application, so cross-platform compatibility is already out of the question.  I have gone through the msdn documentation and I just can't understand, for example, why anybody would decide to use _beginthread instead of CreateThread or vice versa.  Cheers!  Update: OK, thanks for all the info, I've also read in a couple of places that I can't call WaitForSingleObject() if I used _beginthread(), but if I call _endthread() in the thread shouldn't that work? What's the deal there?
78110
Is there any advantage of using     instead of  ?   As far as I can tell the following fragments are almost equivalent:  1. Semaphore  final Semaphore sem = new Semaphore(0); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         sem.release();       }     }   };   t.start(); }  sem.acquire(num_threads);   2: CountDownLatch  final CountDownLatch latch = new CountDownLatch(num_threads); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         latch.countDown();       }     }   };   t.start(); }  latch.await();   Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)  So in what situation might the latch be preferable?
27214
How can I return to the start of a line and overwrite what has already been output on the console? The following does not appear to work:  System.out.print(mystuff+'\r');