best way to handle multiple threads in a Win Forms Application - c#

We have an application with multiple subsystems running in different threads (ie one thread monitors the GPS, another monitors a RFID reader etc). The threads are started and monitored by a service registry which is seperate from the win forms part.
The initial release of the App just had a single form which would run on an update timer and just check the values of static variables on each of the subsystems every second or so.
I'm trying to clean this up, as we're adding in extra forms and there's virtually no thread safety with the current approach. I want each subsystem to throw a new event when its underlying state has changed so each form can subscribe only to the events it cares about and we can move to a more responsive UI...I don't like the update timer approach.
I'm running into problems here as events are triggered in the subsystems thread so I get System.InvalidOperationException exceptions complaining about cross thread calls when I try and update the UI with any state that is passed through with the event.
So at the moment, after reading through the msdn documentation, my options are to use control.invoke for each field I wish to update which is pretty annoying on complex forms with lots of fields, use background workers to run the subsystems in the forms themselves or have the forms still run on a timer and query the subsystems themselves, which I'm trying to avoid. I want the forms to be as separate from the underlying system as possible...they should only know which events they care about and update the relevant fields.
My question is, what am I missing here?? is there a better way I can architect this system so that the subsystems can run in their own threads but still send notifications off in a non coupled way?
any help would be greatly appreciated
cheers
nimai

Rather than invoke across for each field you want to update, use a MethodInvoker delegate with BeginInvoke and call a method that does all your updates at once. For example ...
BeginInvoke( new MethodInvoker( MyUIUpdaterMethodHere ) );

You can take a look at Event Aggregator pattern which basically allows a loosely coupled pub/sub type event-based architecture. Prism, a framework from Microsoft Patterns and Practices team for building composite applications with WPF and Silverlight has event aggregation that allows different UI components to communicate with each other in a loosely coupled way similar to your design goal. You can take a look at it and try to use just the event aggregation part of it. If not, you have access to the source code so that you can craft something that fits your requirements.

You could use Windows Forms Synchronization Context to pass in a SendOrPostCallBackDelegate(or a lambda) which in turn can update multiple controls in a thread safe manner.
It sounds like these subsystems are running as a windows service.
How is your winform app communicating to these sub systems.

Related

BackgroundWorker vs. Android Service in Xamarin

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/

0MQ windows GUI best practice

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.

Find which module is blocking the UI thread

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.

.NET: Mechanism for sync-ing long-running tasks

Problem description: you write a library which contains some algorithms/tasks which can take a long time to finish, for various reasons: computational, file system, network communication etc. You want to be able to:
Send some progress information about the task (progress, activity logging etc.)
Have a way to abort the task before completion if some external signal or property has been set.
I've implemented a framework for this, but this requires that all such tasks have to reference an assembly which contains this framework.
My question: is there an already built-in mechanism in .NET framework (3.5 or below) for the problem described above?
I know I could use events, but this would mean long running tasks would have to expose such events, which I think is an overhead. Ideally I want to have a framework which hides away multithreading issues and is dependency-injection friendly, but would not depend on an additional custom assembly and would not pollute the original interface.
I hope I described the problem well enough. If not, I can post some samples of the interfaces from my own framework.
UPDATE: OK, I think my problem description needs a bit of clarification :). When I say "long-running", I don't mean "long" in the workflow-sense. I'm working on a WinForms mapping app which does all sorts of stuff, like generating relief contours. To do this, it first has to download the elevation data files from a FTP server, unzip them and then perform some calculations. I wrote the code for this a long time ago, but in order to make it more GUI-friendly, I have to retro-fit various checks - for example, detecting that the user has clicked on the Abort button and stop the process.
So basically my concern is: how to write a code that can later (if ever) be used in a GUI environment, where you cannot simply run everything in the main GUI thread and freeze the whole application. The challenge is to find a way to make your code suitable for GUI purposes without tying it to a particular GUI platform.
That sounds a lot like Windows Workflow Foundation.
Take a look at the saga pattern. It's not built into the framework but can be implemented. Alternatively both NServiceBus and MassTransit have implementations of this. Arnon RGO has a draft from his book (will it ever be finished) describing it here.
In my experience getting going with NServiceBus is much simpler than WF, and is also more powerful (though I haven't looked at WF 4, which by all descriptions is a near complete rework of WF as Microsoft have recognised the failings of this).
Even if you don't want a framework like NServiceBus or MassTransit, the pattern itself, is well worth looking at as it fits your problem space very closelyfrom what you have described.
It depends on how complicated your system is. For relatively simple problems, you could probably nicely use the BackgroundWorker class from .NET 2.0. It supports reporting the progress of the operation using OnProgressChanged event and it also supports cancelation of the background task using CancelAsync method.
The class is controlled by events, but since that's already a part of the class, I don't think it is any overhead for you:
var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
bw.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
The DoWork method is executed to run the background task (it can report progress by calling bw.ReportProgress and check for pending cancellation using bw.CancellationPending).
The RunWorkerCompleted method is executed on the GUI thread when the operation completes (which gives you a nice way to synchronize without worrying about concurrency)
The ProgressChanged event is triggered whenever your DoWork method reports some progress change.
For simpler problems, I believe you could represent your tasks as background workers.
I prefer to use callback methods to signal the UI thread when something's done or progress needs to be updated. You can pass complex objects and the callback can return a value in case it needs to signal the worker thread. And you're allowed to have multiple callbacks defined depending upon how chatty you need your workers to be.

Interacting with UI threads in Java/J2ME

I'm writing a J2ME application. One of the pieces is something that polls the contents of a directory periodically, and, if there are any new things, paints them on the screen. I've done this by having the UI form launch a polling thread with a pointer back to itself, and when the polling thread finds something it calls back to the form and calls a syncrhonized method to update it's display. This seems to work fine.
The question I have is this. In C#/.NET I know it is not nice to have non-UI threads updating the UI, and the correct way to handle this is to delegate it up to the UI thread.
E.g. the following:
public void DoSomeUIThing()
{
if (this.uiComponent.InvokeRequired)
{
this.uiComponent.Invoke(someDelegateThatCallsBackToThis);
}
else
{
this.uiComponent.Text = "This is the update I want to happen";
}
}
Is there a J2ME equivalent for how to manage this process? How about Java? Or does Java/J2ME just play nicer in regard to this? If not, how is this done?
[EDIT] It appears that Swing supports what I'm asking about via the SwingUtilities.invokeLater() and invokeAndWait() methods. Is there an equivalent framework for J2ME?
Regarding Java, what you are describing looks like a SwingWorker (worker thread).
When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads.
A Swing program includes the following kinds of threads:
Initial threads, the threads that execute initial application code.
The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
Worker threads, also known as background threads, where time-consuming background tasks are executed.
Single-thread rule:
Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
When used in a J2EE context, you need to be careful when you are referencing a SwingWorker from an EJB.
Regarding J2ME, it depends if you are developing your application as a standard MIDlet that will run on any MIDP-enabled device, or for instance as a RIMlet, a CLDC-based application that uses BlackBerry-specific APIs and therefore will run only on BlackBerry devices.
Because unlike MIDP's UI classes, RIM's are similar to Swing in the sense that UI operations occur on the event thread, which is not thread-safe as in MIDP. To run code on the event thread, an application must obtain a lock on the event object, or use invokeLater() or invokeAndWait() – extra work for the developer, but sophistication comes with a price tag.
But for LCDUI, you can access a form from multiple threads.
There are many profiles of Java ME. If you mean MIDP then Display.runSerially is what you want.
For AWT (Swing) you would use EventQueue.invokeLater (SwingUtilities.invokeLater is only necessary due to Java 1.1 not having the EventQueue method - 1.2 is about to celebrate its tenth birthday). For the Common DOM API, use DOMService.invokeLater.
No matter what claims a GUI API may make about thread-safety they are probably wrong (some of the claims of Swing are removed in JDK7 because they are not implementable). In any case, application code unlikely to be thread-safe.
For j2me apps you probably want to keep it simple. The main thing is to touch UI components only in the event thread. The direct way of doing this is to use invokeLater or invokeAndWait. Depending on your libraries you won't have access to anything more than that. In general if these aren't provided in your platform it probably equates to there being no thread support and not being an issue. For example the blackberry does support it.
If you develop under SWT this is accomplished by means of asyncExec() method of Display object. You pass an object implementing Runnable so the UI thread executes the changes done in other thread.
This is an example borrowed from here
public void itemRemoved(final ModelEvent me)
{
final TableViewer tableViewer = this.viewer;
if (tableViewer != null)
{
display.asyncExec(new Runnable()
{
public void run()
{
tableViewer.remove(me.getItem());
}
}
}
}
I can attest that the MIDP UI toolkit is indeed thread-safe, as I have large MIDlets with complex GUI running on millions of phones made by almost every manufacturer, and I have never seen a problem in that regard.

Categories

Resources