I currently have a console application written in Visual C# (2013). It opens up a connection to a USB Multimeter and then writes out the value to the console. I would now like to make this into a proper WinForms or WPF application (Data gets recieved, data gets sent to UI thread, data gets displayed in a table/graph etc). To do so, I need to receive the data on a seperate thread, as the data is sent through every 0.12ms (Which would lock up the UI on the main thread).
I have done some reading on both Threading and Async tasks, and as yet, have not decided which would be best suited to the task. Which of these (Or other methods) would be your method of choice for implementing this?
Please note, I am not asking people to write my code for me, I am simply asking which is the best method.
Asryael, your applications sounds fun. To beautify it you can create a WPF MVVM application.
It is not hard as it sounds.
Here is a basic tutorial:
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
The basic idea:
xaml -Defines the ui. Make it nice as you wish.
Then Have a variable in your xaml data bind to a property (variable)
update the variable in a thread everytime you get updates from your usb multimeter.
Have fun. Your application sounds like fun...
Related
I'm currently busy writing some c# code to interface with an Arduino. The code periodically samples audio and transmits data to physically represent the audio levels. I've created a WPF interface for this program, but I pretty much am at a dead end with the final steps. In my interface i would like to be able to change parameters for what is being transmitted as well as displaying feedback read from the COM port.
I don't really understand how to properly make threads in c# - I can imagine how you would create a separate process to manage the IO here as the COM port can only be operated on by a simple process. How would i simultaneously run a loop to sample my audio and send it and another loop to read the serial port, all while still remaining separated from the WPF process so the UI doesn't freeze.
Any tips about proper practice to create these threads securely and efficiently is massively appreciated too!
Thanks
The simplest model is to use a few separate Threads. Each thread runs in an infinite loop, which is defined in a method called a TreadProc, and so each Thread is like a seperate program, but it runs in the same Process and can interact directly with the UI.
These background threads can interact with the WPF UI through the UI Elements' dispatchers. See Threading Model - WPF
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.
I'm writing a class which would handle all the serial communications with a external device (i.e. reading and writing). The data is being streamed to the computer at 20Hz, and occasionally data is also written to the device. The class would then output valid data through an event to the main UI.
I want to put this class in a separate thread because my previous code caused some 'stuttering' in the device since it was in the main UI thread.
I'm just unsure of how to structure and implement the SerialPort class with a thread/background worker because I'm inexperienced in this area.
Would only the data received event exist inside the thread/background worker?
How would you pass data in and out of the created thread/background worker?
Any hints or suggestions would be much appreciated!
My first tip is that you should think of it like it was network (Socket) communication. The threading issues are much the same. Looking thru the MSDN documentation they have (if I remember correctly) two different ways of doing this, async and sync. I personally would use one of the async ways.
You can also take a look at the new Task library.
Start looking in to that and come back if you have further questions =)
Also from the msdn library serial port with threading example this is to console, but anyway.
You just implement in another thread the actual use of the SerialPort. When the time comes to "notify" your UI, you use "BeginInvoke" to get the actual UI handling to run inside the UI thread.
Something like:
string s = _port.ReadLine();
form.BeginInvoke((MethodInvoker)delegate
{
_textbox.Text = s;
});
Just use the DataReceived event.
My application connects to MySQL but sometimes it takes a while and the GUI is getting frozen. I would like to do the connection on the other thread, I guess BeginInvoke would be the best way (I know about background worker but I would like to learn this). I have studied MSDN page but I did not understand what is the best way to use?
They also say that you can use only callback when the thread that called the async.method does not need to know the results...I dont understand it as I believe I can set some variable in the other thread to "pass" the result well.
I would just need the GUI to be not frozen while the connection is being established. Thank you for your advice.
By far the easiest way to handle it is to use a BackgoundWorker. It is specifically designed to take care of most threading issues such as marshalling progress events and completion notices from the background thread to the GUI thread. I've used it to great success with both WinForms and WPF.
I know many other methods for doing this, but they all take two or three attempts for me to get right.