I have some commercial equipment that I can connect to with a .Net library supplied by the equipment manufacturer - so I have no control over the library or the equipment, only my code.
The manufacturer has set their system up so that if you are not connected to the equipment via their library then it works fine. However, when you do connect with their library there is an implicit requirement that you service Windows message pump at a rate set by how fast the equipment is running. This is because their library implements an event system that you can subscribe to that tracks operation of the equipment, but they assume that your application code will be WinForms based. (But there is nothing explicitly stating this in their documentation - only that all 2 of their .Net example programs are WinForms based.) I have confirmed with their tech support that the expectation is that you will use a WinForms application.
In my case I am writing a C#, non-WinForms based application (actually a Windows Service, so I do not have a UI thread) and even though I am connecting to the equipment I am not subscribing to any of the events. As a result I have found that I need reference the WinForms assembly and call Application.DoEvents() at a fast enough rate to service all of those events that I do not subscribe to.
So my questions are these:
In this case is calling Application.DoEvents() my only option?
Or is there a more modern way of doing this?
What are the ramifications of calling DoEvents() on a 20mS rate?
Unrelated, but if I wrote a WPF based application would that program be likely to service the message pump?
Edit
I should add that if you connect to the equipment and do not service the windows message pump (even if not subscribed to any of their events), then the equipment falls starts to behave unpredictably.
Edit 2
Also the thread I use to interface to the library is about 2 or 3 generations removed from the initial windows service thread.
This is fine, the usual caveats for DoEvents do not apply here because you don't have a UI. There are no ramifications, the rate is realistic. Application.Run() also pumps the message loop but you'll have a harder time controlling the thread since the call doesn't return. Yes, WPF pumps the message loop too but there's little point in using it since you don't have a UI.
You should initialize the service thread by calling SetApartmentState() to select STA. This ensures that any COM server works properly.
Oh, one caveat that jumps to mind: you do need to do something to prevent the thread from burning 100% core. It is automatic with Application.Run() but not with DoEvents in a 'game loop'. I think you already do since you can specify a 20 msec rate. Otherwise, calling WaitHandle.WaitOne(20) on the service stop request event is the typical approach.
You can have a message pump without forms just call the version of Application.Run() that takes a ApplicationContext or no parameters on a thread.
EDIT: I would recommend the ApplicaitonContext version so you can call ApplicationContext.ExitThread() in the OnStop() of your service.
Related
I am writing a library (a .NET Framework DLL).
This library can be used in various kinds of applications: WinForm applications, WPF applications, ASP.NET applications, Windows services, ... even unmanaged applications (via COM interop).
This library creates a background thread to do some maintenance tasks.
Here's the challenge: When the main application is closed, my background thread needs to detect this and do some cleanup to exit gracefully (close database connections, etc.).
How can my background thread detect (in a host-application-agnostic way), that its process is about to terminate, so that it can start its cleanup tasks?
Prior research:
There are multiple ways to detect that the application is closing for specific UI frameworks (e.g. Application.ApplicationExit for WinForms and Application.Exit for WPF). Obviously, that's not suitable for a generic library.
You can attach a handler to the AppDomain.ProcessExit event of the current application domain.
However, you need to be quick with your clean-up (quote from the documentation, emphasis mine):
In .NET Framework, the total execution time of all ProcessExit event handlers is limited, just as the total execution time of all finalizers is limited at process shutdown. The default is two seconds.
Often, however, the host application knows when it is about to close, so my recommendation would be as follows:
Add a Shutdown method to your library, and document that implementors should call it before closing the host application. Do your clean-up there. If implementors do as recommended, you don't have a time limit here.
In AppDomain.ProcessExit, call your Shutdown method if it has not been called explicitly before. You do have a time limit here, but it's better than nothing.
This is similar to how the Dispose pattern works: Dispose is called in the finalizer if, and only if, it has not been explicitly invoked before.
I'm writing a Windows Service to run in the background and read data off (via provided C# sdk) of 4 separate USB camera modules which are triggered externally via hardware. I'd like to make relatively modular pieces so we can operate with more or fewer camera modules with ease. As such I'll probably make a "camera reader" class and create as many as I need within the context of the service. For the sake of timing, I also need a separate entity to take all the images collected and write them to disk.
The question I have, not having developed a Windows service or written C# before, is this: Is there any real difference between having such a class contain a timer object and a tick function as opposed to having the class start a thread which loops checking the cameras and calculating a sleep period to do it at regular intervals? The Windows Service examples I keep finding all use Timers for ongoing background tasks.
I have the same question for the entity that writes to disk. That could also be either another timer or a thread, though I'd lean towards thread there as I'd have a queue with a semaphore for it to pull it's work from.
Both ways will work fine (as long as you don't use System.Windows.Forms.Timer, which needs a message loop to work).
This is what MSDN says about timers:
The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:
System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Windows.Forms.Timer, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.
System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
So, use whatever floats your boat!
As for writing the data to disk, having a dedicated thread that keeps a queue and writes the files out one at a time sounds good to me!
I'm investigating about mobile apps using Mono on Visual Studio.Net.
Currently we have an application we want to translate to Android from Windows CE. The original program used small BackgroundWorkers to keep the UI responsive and to keep it updated with the ProgressChanged event. However I have been reading that in Android there are Services that can replace that functionality.
Reading pros and cons about services I know that they are usually used because they have a better priority than threads and, mainly, if the functionality will be used in more than one app.
More info I have found comparing threads and Services say that Services are better used for multiple tasks (like downloading multiple files) and threads for individual tasks (like uploading a single file). I consider this info because BackgroundWorker uses threads.
Is there something I am missing? Basically a service should be for longer tasks because the O.S. gives it better priority (there are less risk it will be killed) and Threads/BackgroundWorkers are better for short tasks. Are there any more pros/cons to use one or the other?
Thank you in advance!
[Edit]
If you need a very specific question... how about telling me when and why would you use a Service instead of a BackgroundWorker? That would be useful.
Some of the functionality I have to recreate on Android:
- GPS positioning and compass information - this has to be working most of the time to get the location of the device when certain events are working and trace in a map its movements.
- A very long process that might even be active for an hour.
The last one is the one I am concerned about. It must be very reliable and responsible, keeping the user informed of what it is doing but also being able to keep working even if the user moves to other activity or functionality (doing a call, hitting the home button, etc.)
Other than that I believe the other functionality that used BackgroundWorker on WinCE will not have problems with Android.
[Edit 2: 20140225]
However I would like to know if the AsyncTask can help me in the next scenario:
- The app reads and writes information from/to another device. The commands are short in nature and the answer is fast so for individual commands there is no problem. However there is a process that can take even an hour or so and during that time it will be asking the status from the device. How would you do it?
I think you're misunderstanding what a Service in Android is. See the documentation on Services:
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.
Also note:
A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise).
Using a worker thread and using a Service are not mutually exclusive.
If you are looking to move work off the main thread, then clearly you need to use another thread. Through a BackgroundWorker or perhaps the TPL will do just fine in many cases but if you want to interact with UI (e.g. on completion of the task or to update progress in the UI), the Android way is to use an AsyncTask (mono docs).
If this work needs to continue outside of the user interaction with your application, then you may want to host this work (including the BackgroundWorker/Thread/AsyncTask/etc.) in a Service. If the work you want to do is only ever relevant while the user is interacting with your application directly, then a Service is not necessary.
Basically, a service is used when something needs run at the same time as the main app - for example keeping a position updated on a map. A thread is used when consuming a webservice or a long running database call.
The rule-of-thumb, as far as I can see, is rather use threads and close them, unless there is something that needs to happen in the background (like navigation updates). This will keep the footprint of the app smaller, which is a large consideration.
I hope this helps at least a little.
Now that you know you don't need a Service, I want to point out how is the Xamarin guideline doing/recommending this: create a separate thread using ThreadPool and when you want to make changes to GUI from that thread, you call the main thread to do them using the RunOnUiThread method.
I'm not sure that by using AsyncTask you can write your code inline in c#, but with Xamarin recommendation you certainly can, like so:
//do stuff in background thread
ThreadPool.QueueUserWorkItem ((object state) => {
//do some slow operation
//call main thread to update gui
RunOnUiThread(()=>{
//code to update gui here
});
//do some more slow stuff if you want then update gui again
});
http://developer.xamarin.com/guides/android/advanced_topics/writing_responsive_applications/
I've a pretty simple question/issue. I want to use 0MQ for some pretty basic Pub/sub functionality. My subscriber app is a windows GUI based app using plain winforms.
As there seems to be no explicit reference in 0MQ for handling this scenario, I am assuming that worst case I'd have to use a BeginInvoke(...) on the windows GUI thread once the 0MQ thread has recieved any subscription message. This seems pretty straightforward but if anyone has any insight/opinion/heads up in terms of the best way to handle this I'd very much appreciate it.
Thanks in advance
David
For your ZeroMQ subscriber in a WinForms application you have at least a few options:
Use a background worker thread to receive your 0MQ message. When you receive a message pass it to your background worker progressChanged event to update your UI.
Use a system thread to receive the message and invoke to update your UI.
Another suggestion on SO also suggest using a system thread to queue the message upon receive and a timer event to dequeue the message. If you used a Forms Timer you could update the UI without invoking or if System Timer you would need an invoke.
Which method you choose depends on your design criteria.
As pointed out, there are several ways to hook up ZeroMq into a WinForms app. It really does not differ much from using ZeroMq and C# in other settings, like in a console application. The main difference is as you point out that you have to get the messages into the Gui thread in order to update your Gui controls.
An example of using a separate thread + queues (producer/consumer pattern) can be found here: Examples of zeromq pub/sub with C# winform
Another way could be to use (again) a separate thread to do the ZeroMq work and set up an event that gets fired each time a message is received. The Gui could then hook up an event handler and process the message. You would of course also have to invoke any updates to the Gui. A drawback to this approach is that the event processing will interfere with the ZeroMq handler thread a bit, especially if the Gui updates takes a while, and if you receive lots of data.
All solutions have their pros and cons, it all depends on how your particular problem domain looks. All-in-all, integrating ZeroMq into a C# application, be it WinForms or other, is IMO pretty straightforward. The clrzmq wrapper is well-written and easy to use. The problems you may run into has more to do with the limited error feedback in ZeroMq itself. If you encounter strange crashes; try to run the same logic in a console application, that will give you better error messages.
This is a two part question:
I am working on a big project where multiple plugins developed by different teams are loaded inside one common container shell. At times I can see that my UI updates are blocked as there are multiple parallel UI updates, i want to know if there is a way to find which component is blocking the ui thread
In .net how can i create a separate UI thread which requires dedicated UI intensive work?
Much Appreciate your help. Thanks.
Use the debugger. Debug + Break All when you notice it blocking. Then Debug + Windows + Threads and select the main thread. The call stack window shows you what it is doing.
A corner case is where these plugins are using a lot of calls to Control.Begin/Invoke or Dispatcher.Begin/Invoke. Your UI thread is not blocked in this case, it is just being overwhelmed by requests to dispatch the delegate targets. And doesn't get around to doing its normal duties anymore, like repainting the windows and responding mouse and keyboard events. There's little you can do about this beyond working with the plugin authors to get them to mend their ways.
You've already got an UI thread, the thread that created the first window. Creating additional threads that have their own windows is possible but causes unsolvable problems with window Z-order (a window will disappear underneath the window of another app) and generous helpings of window interop threading misery.
Visual Studio 2010's (in the higher SKUs) include features to check for this. If you run your program under the Concurrency Profiler, you can see exactly which threads are waiting on which locks when the deadlock occurs. In addition, it will highlight the deadlock (I believe in bright red) to make it easy to track down.
One approach you can take (though it may require a bit of redesign) is to disallow all plugin logic from running in the UI thread. All operations that require updates to the UI must be routed through well-defined service interfaces that can interpret, dispatch and perhaps even throttle the UI updates. This is only practical if your plugins are not deeply UI-centric and you have a service model that allows you to isolate the data being manipulated by the plugins from the visualization of that data. Without knowing more about your application, I can't give more concrete recommendations.
Here are two possible solutions to the problem that I came up with quickly. I am sure there are other equally valid solutions though.
Option 1: Instead of using the push model (via the ISynchronizeInvoke methods) switch to a pull (or poll) model in which the UI queries the plugin for updates. This has the following advantages.
It breaks the tight coupling between the UI and worker/plugin threads that Control.Invoke imposes.
It puts the responsibility of updating the UI thread on the UI thread where it should belong anyway.
The UI thread gets to dictate when and how often the update should take place.
There is no risk of the UI message pump being overrun as would be the case with the marshaling techniques initiated by the worker/plugin thread.
The worker/plugin thread does not have to wait for an acknowledgement that the update was performed before proceeding with its next steps (ie. you get more throughput on both the UI and worker/plugin threads).
Option 2: Have the plugin accept an ISynchronizeInvoke instance instead of an actual Form or Control. This special synchronizing object will be implemented using a dedicated thread and a queue that acts as buffer between the plugin and the UI. It will accept update messages via the normal Invoke or BeginInvoke methods, which means you can keep the plugin architecture and interfaces mostly intact, and then forward those messages on to the UI after some type of filtering, merging, and throttling operations have occurred. The number of update messages existing in the synchronizing object will ebb and flow as the UI and plugin threads work load changes. It could be smart enough to change its forwarding strategy as the rate of messages increase.