Using threads in a solution in c# for IO - c#

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

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/

Best method for handling asynchronous USB data requests?

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...

Data handeling with c# chart control

I have a quick question for you all. This is my first time dealing with serial I/O, and was wondering what the most efficient method is. Ill be reading in from a laser through rs-232.
From what I can tell from researching it I can accomplish this by using a background worker to create a buffer from the serial port, then have the main thread access that buffer to plot and analyze the points. Is there a more efficient / reliable way to do this ,or is this approach going to be my best bet?
thanks!
How you read from the device depends on how data is retrieved from it. I have an application that gets data from a strain gauge (attached to a meter). This meter autonomously spits out readings, so I don't have to poll it. Because of this I simply use the SerialPorts DataReceived event and add data to an array.
I use the Microsoft Chart Control (built into .NET 4.0) which lives on the UI thread, so it has to be updated from the UI thread. The data comes in pretty fast (~100 points per second), so what I do is build a 100 point array and BeginInvoke (Winforms) that array off to the UI thread while starting a new array. This way the UI is updated periodically (~1 update per second).
If, on the other hand, your device requires polling (you have to ask it for data each time), then you'll want a dedicated thread that sits in a tight loop polling.

Implementing Thread in Java from a C# background

I'm trying to implement multithreading in my Java GUI application to free up the interface when a couple of intensive methods are run. I'm primarily from a C# development background and have used Threads in that environment a couple of times, not having much difficulty of it all really.
Roughly:
C#
Create a Thread object
Assign it a method to start from
Start thread
Now onto the Java app itself, it's a GUI application that has a few buttons that perform differrent actions, the application plays MIDI notes using the MIDI API and I have functions such as play, stop and adding individual notes. (A key thing to note is that I do not play MIDI files but manually create the notes/messages, playing them through a track).
There are three particular operations I want to run in their own thread
Play stored MIDI notes
Display a list of instruments via a text box
Generate 100 random notes
I have a class called MIDIControl that contains all of the functionality necessary such as the actual operations to play,stop and generate the messages I need. There is an instance of this object created in the FooView.Java class for the GUI form itself, this means for example:
Press "Generate"
Event handler performs the "GenerateNotes" method in the FooView.Java class
This method then performs the "Generate" method in the MIDIControl instance
I've looked at implementing threads through Java and from what I've seen it's done in a different manner to the C# method, can anybody explain to me how I could implement threads in my situation?
I can provide code samples if necessary, thanks for your time.
Java threads are created the same way as C# threads, except that you pass the thread a Runnable implementation instead of a delegate. (Because Java doesn't support delegates)
Java Concurrency in Practice is your guide. Pls also have a look at SwingWorker. Remember that all UI related changes (either component model or its properties) should always be done on Event Dispatch Thread.
Background tasks in Java GUI applications are often done using the SwingWorker class, which is designed specifically for that purpose.
You'll need to distinguish between tasks that update the GUI, and tasks that do not.
If your task needs to update GUI elements, such as your task (2), you'll need to sub-class SwingWorker. The processing code (calls to your exising library) go in your override of doInBackground(), sending out any data through publish(). Then, your SwingWorker process() override can interact with your Swing components.
The reason: Swing is not thread-safe, so it will potentially break if accessed from threads other than the Event Dispatch Thread (EDT). process() will run in the EDT.
For tasks that don't update the GUI, create a new class which implements Runnable and insert the appropriate MIDI library code call in the run() method. You may then pass this as a target to a new thread as in new Thread(myRunnable).start().
As others have said it's the SwingWorker class you're after, this will enable a swing component to fire off a task in another thread and be notified of its completion and progress in a thread safe manner. You can't just spout off random threads using the raw thread runnable objects and then expect to interact with swing through those threads; swing is not thread safe by design so by doing things this way you'll almost certainly introduce subtle threading bugs into your code.
Depending on what version of Java you're using you can either download the SwingWorker separately or use the one built into the API.
If you're using Java 6 (or above) then swing worker is in the core API here.
If you're using Java 5 then the Java 6 version has been backported here.
If you're using an earlier version then you'll have to add sun's original version in which is here.

How to implement SerialPort with thread/background worker C#?

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.

Categories

Resources