I think a Thread is still alive after application closed ( C# ) - c#

I have an C# application that is using few threads (specially for showing graphic chart and get data from a device).
After some uses my app becomes slower and I must restart computer to solve this problem.
How can I solve this problem?

There is two types of Thread. They are Background and Foreground. If your threads are Foreground the application will not close until all foreground threads are finished.
https://learn.microsoft.com/en-us/dotnet/standard/threading/foreground-and-background-threads
And you should dispose all your unmanaged resources as #opewix says.
What is IDisposable for?

Can you ensure that your application in not running in the background when you close it. You may check it in TaskManager. If it is not there, the process was terminated and all threads that belong to app are terminated too.
There may be some unmanaged resources that your app didn't release.

Related

What to do if I need a disposable object to stay present until my console application has ended?

I have read a couple of threads asking this question but that involve Windows Forms applications. Forms applications have functions that are called when they are closed, which makes it easy to dispose of objects on application termination. I have an event-based console application that will be continuously running in the system's background similar to a service. The only way to end the program will be to end the process through the task manager. I accomplished this by calling Console.Read after all logic in main() and hiding the console so that it runs indefinitely.
I have a Timer object that I want to make sure gets disposed of, but since there is no official exit to my program, I do not know where to dispose of it. Would it be okay to let the operating system dispose of it since only a single class depends on it? I have read that it is dangerous to override the finalize() function, and don't want to do anything too tricky. There will only be one instance of my application running over long periods of time (until the system shuts off or until I push out an update).
As you are killing the process, there isn't any code where you could dispose the timer, but you don't need to worry about it.
When the process is stopped, everything in its memory space goes away. The process runs in a separate virtual memory space, and that entire memory space is removed when the process is stopped.

Windows UI/Application freeze when running 24X7

I have developed one application in C#.net 3.5 and VS 2008, which contain many controls such as tab, textbox, objelistview, gauges, zedgraph.
My application is intended to communicate on serial port and update the data on said ui. To achive this i am using another timer thread.
Its 24X7 running application, but sometime it just freeze and timer thread stops executing automatically, i can see the sceen but can't click anywhere and simply i need to restart application to make it run again.
Please note i dont see application not responding message or likewise, it just simply freeze.
If any one can provide any inputs for the same it would be great.
You may have memory leaks or too many uncolsed resources. While your application is freezed see Task Manager and check Memory and CPU usage. They can help you gueesing if too many of RAM is used or if your application consumes too many CPU processing power.
In your application consider disposable objects. Try to dispose them correctly. After opening a serial port don't forget to close it again. Also you can use logging mechanisms to see at what point your application freezes.
Try implementing a watchdog using System.Threading.Timer and check if thread responsible for communication is responsive. Also, I'm not sure what do you mean by "another timer thread", but again, you should use aforementioned class to track time between datapolls and use callback method.
Please also remember, like afsharm said, that you need to free resources you don't use anymore, so either get one handle on your COM port and use it or just release it everytime update has ended.

Does Thread runs when application is closed?

I have a window (C#) application (only .exe file, no code) which uses a thread.
If my application is closed mean I am not using that application.
Is thread working backword at this time or not?
My Problem is that I am transferring a file from one drive to another drive at a particular time using timer thread class, at that particular time application is closed.
File will transfer or not?
No it wont. The thread was started in application and if application is closed all threads in it are killed.
Any threads that you start in your program, prevent the application from terminating, until all the treads have exited their thread proc function, or have abort() called on them.
To examine the exact way the timer thread class works, run the demo code that is located on the MSDN
http://msdn.microsoft.com/en-GB/library/ms149618.aspx
As people have pointed out, set background threads will not prevent application from termination, however, having a thread as a background thread, would not achieve what the op wanted.
No, threads only exist if your application is running. You need to create a completely separate background process (not just a background thread) if you want something to continue after your main application exits

Interface freezes in multi-threaded c# application

I have a c# .NET multi-threaded application that is freezing the interface. What is unusual about this is that the interface does not freeze unless I let the system sit idle long enough for the screen saver to start (which requires me to reenter my password to re-gain access to the system). When the interface becomes visible again (after I have successfully entered my password) the interface is locked up. As long as I don't let the screensaver start, then the interface does not lockup.
I should point out that I have two different executables that access the same dll and this problem is occurring no matter which application I use to access the DLL. This seems to imply that the problem is in the DLL as the two applications are completely different (C++/MFC) and (C#/.NET) apart from how they relate to the DLL.
Both exes perform similar steps in how they interact with the DLL. They make calls into the dll to setup the serial port communication, open a status window in the DLL, start a thread in the DLL to monitor the comm port, and then starts a thread in the main app that monitors a stack in the dll.
When data is obtained from the comm port by the thread in the DLL, it is parsed and its results are placed on the stack and then posted to the status window via a delegate. When the thread in the exe sees data in the stack, it outputs the data in the main window, also using a delegate.
I found that if I add code to the thread inside the DLL so it calls Application.DoEvents() every 30 seconds, the interface will be frozen for about 30 seconds and then resume activity like normal.
I figure something is blocking the main thread and forcing DoEvents() to fire seems to break the lock, but I have no idea what might be causing this lock.
This issue occurs both on my development machine and on a test machine.
I have tried completely removing the output of data to the status window inside the DLL, but that didn't make any difference.
I have been doing multi-threaded programming for years and never seen anything like this; so any advice would be greatly appreciated.
Thanks.
This is a problem that's commonly induced by the SystemEvents class when you have a non-standard way to initialize your user interface. Using threads, specifically. Start your program, Debug + Break All, Debug + Windows + Threads. If you see a thread named ".NET SystemEvents" then you're pretty much guaranteed to get this hang.
Some background: the SystemEvent class supports both console mode apps and GUI apps. For the latter, it should fire its event handlers on the UI thread. The very first time one of its events is subscribed, it creates a little invisible helper window to get the system notifications. It can do this two ways, either by creating the window on the calling thread or by starting up a helper thread. It makes the decision based on the value of Thread.GetApartmentState(). If it is STA then it can create the window on the calling thread and all event callbacks can be properly marshaled to that thread.
This goes wrong if the first window you create is not created on the UI thread. A splash screen for example. That window may contain controls that are interested in a system event like UserPreferenceChanged so they can properly repaint themselves. It now uses the helper thread and any event will be fired from that helper thread, not the UI thread. Poison to any window that runs on the UI thread. The session switch out of a locked workstation (including the screen saver) is for some mysterious reason very likely to cause deadlock. You may also see an occasional painting mishap, the less nasty result of using windows from the wrong thread.
Short from fixing the initialization order, a workaround is to put this in your Main() method, before any windows are created:
Microsoft.Win32.SystemEvents.UserPreferenceChanged += delegate { };
The problem does appear to be related to the ActiveX control is was probably using incorrectly in a form. I switched to using the serial port library in .NET and have not been able to reproduce my problem. Thanks to everyone, especially Hans for their assistance.
I am having the same issue as my PC just hangs up when the screen saver kicks off or I lock my PC and monitor goes to sleep.
I am 95% sure that there are deadlocks appearing in my multithreaded app. Look and identify whether there are any deadlocks in your code.

C# .Net exe doesn't close when PC is restarted, keeping the machine from restarting

We have a SmartClient built in C# that stubornly remains open when the PC its running on is being restarted. This halts the restart process unless the user first closes the SmartClient or there is some other manual intervention.
This is causing problems when the infrastructure team remotely installs new software that requires a machine reboot.
Any ideas for getting the SmartClient app to recognize the shutdown/restart event from Windows and gracefully kill itself?
UPDATE:
This is a highly threaded application with multiple gui threads. yes, multiple gui threads. Its really a consolidation of many project that in and of themselves could be standalone applications - all of which are launched and managed from a single exe that centralizes those management methods and keeps track of those threads. I don't believe using background threads is an option.
OK, if you have access to the app, you can handle the SessionEnded event.
...
Microsoft.Win32.SystemEvents.SessionEnded +=new
Microsoft.Win32.SessionEndedEventHandler(shutdownHandler);
...
private void shutdownHandler(object sender, Microsoft.Win32.SessionEndedEventArgs e) {
// Do stuff
}
It must be a thread that continues to run preventing your application to close. If you are using threading an easy fix would be to set it to background.
A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.
http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx
When a user is logging off or Windows is being shut down, WM_QUERYENDSESSION message is sent to all top-level windows. See MSDN documentation here.
The default behavior of a WinForm application in response to this message is to trigger the FormClosing event with CloseReason == WindowsShutDown or others. The event handler though can choose to be stubborn and refuse to shut the app down, thus keeping the system running.
Check FormClosing handlers of your applications. Maybe there is something in there. I've seen this kind of stuff a couple of times.
Or maybe the .Net app is ignoring close or quit messages on purpose?
Background threads was a quick and dirty solution, best solution is to use synchronization objects (ManualResetEvent, Mutex or something else) to stop the other threads;
Or else keep track of all your opened windows and sent WM_CLOSE message when main app closes.
You have to give more information about how do you start those GUI applications. maybe you start one thread for each application and call Application.Run(new Form1()); ?
You may also look into creating a AppDomain for each GUI Application
Normally a .Net app would respond correctly- at least, that's the 'out of the box' behavior. If it's not, there could be a number of things going on. My best guess without knowing anything more about your program is that you have a long-running process going in the main UI thread that's preventing the app from responding to window messages.

Categories