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.
Related
I'm new to programming in Windows CE 6.0 on an ARM-based 32-bit processor using C# and .NET 3.5 Compact Framework. I'm supposed to be creating a user interface that shows information coming from different threads in a heavily multi-threaded program (think of an update to a status board or to a game loop). Using tricks I've done on more typical Windows desktop applications, I launch my Windows form on its own thread and update the appearance in a Paint event handler.
I've got an API that the other threads can call (it's thread-safe, as far as I can tell - locks on shared data items, etc.), and the calls that update the data structures then trigger an Invalidate() on my Windows form. My expectation is that sometime (soon, hopefully) my form gets told to repaint and it updates the screen with the latest data that's been provided.
Only I'm not getting as rapid a refresh rate as I would expect. I even put in a timer that triggered Invalidate() 30 times per second and I didn't get more frequent updates, even in a simplified setup. In a more vicious setup, where I launch a thread that's basically doing while (true) {}, then my Paint event NEVER gets called (not a surprise there, really, but still...). So I'm not sure whether I'm not understanding something about the environment my program is running in (VERY possible), or if there are some other things I need to account for in Windows CE that I'm not aware of currently. I've spent a lot of time with Google and reading lots of SO responses and various blogs, etc. My display refresh is still slower than I need.
I realize this is somewhat vague. What I'm trying to understand is if there are some tricks that I need to understand about Windows CE 6.0 and it's implementation of multi-threading and Windows Forms, etc., to see if there are ways to improve the refresh rate of my form painting (and ideally ensure that it gets called at least once a second, for example).
I am not sure if this helps but consider this:
Do not run threads without a sleep inside. DO/While(TRUE) is bad. Windows CE is multithreaded but the time slices given to a thread depend on co-operation of all threads giving the OS the chance to yield to another thread.
Do not use invalidate or refresh on the whole form. If you have a list of informations to display from different threads only let a thread update its portion of the GUI.
You may use SendMessage to update the GUI instead of PostMessage (in contrast to use events/delegates). SendMessage will block until msg is processed, so use it only from background thread. But SendMessage will ensure the fastest update on the GUI thread (if used for portion of screen).
You may even decouple the background threads and the GUI using a message queue. So post all updates of threads into the queue and on the GUI peek the message to make changes to the GUI. Again, do not run background threads without a Sleep or WaitObject inside.
You may use invalidate/refresh to update the GUI, but use it on single controls only. In example: you have a number of labels showing thread values, when a thread value is to be updated then only invalidate/refersh the label assigned to the thread value and not the whole form.
You may sync GUI updates and threads using events, so a thread is blocked until the GUI fires the event to unblock, for example when the GUI has finished processing the thread's update message.
Note that Windows CE is not a real-time OS. It uses co-operative Multitasking. A single thread can consume nearly all processor time.
Possibly doing a win32 API app will enhance speed as Compact Framework code (IL, GarbageCollection etc) is slower than native code.
I currently have an application which is basically a wrapper for ~10 "LongRunning" Tasks. Each thread should keep running indefinitely, but sometimes they lock up or crash, and sometimes the wrapper app spontaneously exits (I haven't been able to track that down yet). Additionally, the wrapper application can currently only be running for one user, and that user has to be the one to restart the threads or relaunch the whole app.
I currently have a monitor utility to let me know when the threads stop doing work so that they can be manually restarted, but I'd like to automatically restart them instead. I'd also like the wrapper to be available to everyone to check the status of the threads, and for the threads to be running even when the wrapper isn't.
Based on these goals, I think I want to separate the threads into a Windows Service, and convert the wrapper into something which can just connect to the service to check its status and manipulate it.
How would I go about doing this? Is this a reasonable architecture? Should I turn each thread into a separate service, or should I have a single multi-threaded service?
Edit: All the tasks log to the same set of output files (via a TextWriter.Synchronized(StreamWriter)), and I would want to maintain that behavior.
They also all currently share the same database connection, which means I need to get them all to agree to close the connection at the same time when it's necessary. However, if they were split up they could each use their own database connection, and I wouldn't need to worry about synchronizing that. I actually suspect that this step is one of the current failure points, so splitting it up would be a Good Thing.
I would suggest you to stay inside one multithreading service if possible. Just make sure that threads are handled correctly when Service Stop is triggered. Put brake flags inside blocks of code that will take a lot of time to execute. This way you will make your service responsive on Stop event. Log any exceptions and make sure to wait for all threads to exit until service is finally stopped. This will prevent you to run same "task" in multiple threads.
Maintaining one service is in the end easier then multiple services.
Splitting to multiple services would be reasonable if you require some separate functionalities that can run or not beside each other.
I don't think moving the threads to a Windows Service removes any of the problems. The service will still crash randomly and the threads will still exit randomly.
I assume that your long-running tasks implement a kind of worker loop. Wrap the body of that loop in a try-catch and log all exceptions. Don't rethrow them so that the task does not ever exit. Examine the logs to find the bugs.
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.
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) all the windows are white. I can see the window titles, move the windows around, minimize them and such, but the screens are not repainting. When I break all and enter the debugger, the call stack has Application.Run(), external code, and then "in a sleep, wait, or join". I put break points in all four of the threads I open and they are still running, it is just the main app's UI thread that is blocked. When I look at my thread list, what was my main thread and my four worker threads now consists of my main thread and 11 worker threads. I didn't open this many threads so it must be the serialport class.
Now let me describe my program.
My main app allows users to collect and monitor data from serial ports. I have implemented this in the following way. When a connection is desired, a button is pressed on the main app which calls a function in a DLL which opens a status window and then launches a thread which monitors the serial port. When that function returns, the main app launches a thread to monitor a queue created in the DLL when it is initialized. When data is received from the serial port, the data is parsed and then the status window is updated (via a delegate) and the data is pushed onto the queue. When the main apps worker thread sees data in the queue it retrieves it and posts it in a list box on the main app, using a delegate. In all cases I use BeginInvoke to call these delegates.
My DLL contains two libraries for the two different types of equipment it can communicate with.
This problem occurs when I have a connection to two devices; hence the four worker threads two for each device. The DLL itself is setup as a comm object so I can access it easily from a C++/MFC app and a c# app, both of which utilize it.
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 is not a solution, just something of interest.
I would appreciate any suggestions you might have. Thanks.
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 is not a solution, just something of interest.
I would recommend running your program under the new Visual Studio 2010 Concurrency Profiler. This will show you, at runtime, which threads are blocked, and which objects they are waiting on. Thread contention is explicitly marked and highlighted for you.
You can use this to easily determine what code is causing the deadlock on your UI thread.
Try changing your Thread Start code to Thread.Start() instead of BeginInvoke(). BeginInvoke does not keep threads tryky seperate from your UI, as it and it may be interacting strangely with DoEvents. You can read up on BeginInvoke and how it works here: http://www.codeproject.com/KB/cs/begininvoke.aspx
Also, DoEvents is NEVER necessary in an application, and can cause a lot of unexpected behavior. Use threadding with UI calls wrapped in a Control.Invoke(...) statement. If you're using .NET 3.5+, you can make this easy with delegates that look like this: Invoke((Action)delegate() {*code goes here*});
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.