I have developed one application in which i am continuously sending request and reading response at serial port and updating huge GUI comprise of zed graphs, objectlistviews, analog meters.
Currently i am using one thread which is performing request & response at serial port and pushing the data into queue , and another thread which is fetching data from queue and updating the GUI.
for this i am making the use of Autoresetevent(Set and waitone) for notifying the GUI thread when data is available in the Queue.
This is actually sequential operation so whatever data comes at serial port should be immediately updated into GUI. Something like below model
1 Response -> Update GUI -> 2 Response -> update GUI -> 3 Response -> update GUI -> so on ..
Whenever i get any error at the serial port complete model get mess up and GUI is not updated properly.
Can anybody please let me know what approach should be implemented for achieving the above?
As English is not my first language, let me know if anybody needs further improvements in the question.
.net framework 3.5 SP1 and VS 2008
sent methods can be called from gui thread, it is OK. Problem is on receiving. You can simply set checkforillegalcrossthreadcalls to false and directly call main (gui) thread method within serial port's datareceived method. However I would not use this method.
I would prefer calling a delegate method to update GUI.
Related
I have my main Winforms application.
There are 6 Threads working in parrael + main thread, atleast that is what it ment to be .
I have created one Thread that is an Tcp Server, listening on specific port.
listenerThread = new Thread(new ThreadStart(AsynchronousSocketListener.StartListening));
listenerThread.Start();
I have also 5 different Threads that are doing different kind of stuff (for example updating database, counting averages/sums, being TCP Clients etc.)
My question is:
Is it possible that my TCP Server (which is working on one of 6 threads) wont read a message when one of those 5 different threads thread will take the computing power of CPU, and the TCP Server's Thread thread will have to wait ?
Another question: If that could happend, how could i avoid that ?
This is a summary of my comments above
"Is it possible that my TCP Server (which is working on one of 6 threads) wont read a message when one of those 5 different threads thread will take the computing power of CPU, and the TCP Server's Thread thread will have to wait ?"
Received data is buffered to an extent however if your code does not respond in an appropriate time then it could result in dropped data.
The same could be said in a single-core system and another app, say Prime95 is busy not playing nice and calculating prime numbers right next to yours.
Another question: If that could happend, how could i avoid that ?
When handling I/O and I'll focus on TCP here is to perform the minimal amount of processing in your data received handler irrespective of whether that handler is of the form IAsyncResult or async/await.
A good general flow is:
start an asynchronous read
read result of asynchronous read
place result in a queue
loop back to #1
Meanwhile you process the read results from #2 in a different mechanism whether that be a timer; GUI app-idle-loop; or a different thread so long as the thread processing the results has nothing to do with the flow above.
The reason being is that in a scenario involving reasonably high data transfer rates, if you were to read a block of data and then proceed to immediately update that Telerik datagrid UI showing 1000s of rows, there is a high chance that the next read operation will result in dropped data because you didn't respond in a sufficient amount of time.
I'm trying to write a client application, which connects to a server on a specified port and receives data.
I found this fine example, but my problem is that the server is sending me data all the time (not closing the conection), and so ReceiveCallback never ends, because client.EndReceive(ar) never returns 0.
So, my WinForm is freezing during receiving data.
The idea is to monitor all the incoming data and make some callbacks on certain occasions.
I'm new to C#, could you point me to right direction? Multithreading?
Have two threads: one for the user interface, and another that reads from the "infinite socket". The infinite thread loops forever reading from the socket in appropriately sized chunks, perhaps doing some preprocessing. It then uses Control.Invoke() to call a method on the UI thread, passing the chunk to it in a parameter. Make sure the chunks are small enough that the UI thread can process them without locking up, say in 0.1 secs.
I'm looking for less technical and more conceptual answers on this one.
I am looking to build a WPF application using .NET 4.5 for controlling a rover, (glorified RC Car). Here is the intended functionality:
The application and rover will communicate wirelessly by sending and receiving strings - JSON over TCP Socket.
The GUI will display multiple video feeds via RTSP.
A control panel - custom hardware - will connect to the computer via USB and these signals will be converted to JSON before being sent over the TCP connection and providing movement instructions.
The GUI will need to update to reflect the state of the control panel as well as the state of the rover based on data received.
I'm not sure which technologies to use to implement this, but from my research, BackgroundWorkers or Threads, and Asynchronous techniques would be things to look into. Which of these seems like a good route to take? Also, should I use TCP Sockets directly in the application or should/could I use WCF to provide this data?
Any wisdom on this would be great. Thanks in advance.
EDIT:
Here was the final implementation used and boy did it workout great:
Everything fell into place around using the MVVM pattern.
There were Views for the control panel and the networking component which each had a corresponding ViewModel that handled the background operations.
Updating the UI was done via databinding, not the Dispatcher.
Wireless Communication was done Asynchronously (async/await) via TCPListener along with the use of Tasks.
Serial Port Communication was done Asynchronously via SerialPort and Tasks.
Used ModernUI for interface.
Used JSON.NET for the JSON parsing.
Here is a link to the project. It was done over the course of a month so it isn't the prettiest code. I have refined my practices a lot this summer so I'm excited to work on a refactored version that should be completed next year.
As you are using .NET 4.5 you dont need to use Threads and background workers for your project. you dont need to take care of all of your threads. As WPF's Dispatcher is a very powerful tool for handling UI from other threads.
For TCP Communication i would suggest you to use TCP Client and TCP Listner with Async Callbacks. and use Dispatcher for Updating your UI.
For Displaying Cameras over RTSP, Use VLC.Net an Open source wrapper for VLC library good for handling many real time video protocols.
Use Tasks instead of Threads, set their priority according to your requirement.
You don't need WCF for your application.
As far as I can tell (I'm no expert), MS's philosophy these days is to use asynchronous I/O, thread pool tasks for lengthy compute operations, and have a single main thread of execution for the main part of the application. That main thread drives the GUI and commissions the async I/O and thread pool tasks as and when required.
So for your application that would mean receiving messages asynchronously, and initiating a task on the thread pool to process the message, and finally displaying the results on the GUI when the task completes. It will end up looking like a single threaded event loop application. The async I/O and thread pool tasks do in fact use threads, its just they're hidden from you in an as convenient a way as possible.
I've tried (once) bucking this philosophy with my own separate thread handling all my I/O and an internal pipe connection to my main thread to tell it what's happening. I made it work, but it was really, really hard work. For example, I found it impossible to cancel a blocking network or pipe I/O operation in advance of its timeout (any thoughts from anyone out there more familiar with Win32 and .NET?). I was only trying to do that because there's no true equivalent to select() in Windows; the one that is there doesn't work with anything other than sockets... In case anyone is wondering 'why of why oh why?', I was re-implmenting an application originally written for Unix and naively didn't want to change the architecture.
Next time (if there is one) I'll stick to MS's approach.
I have created a simple form which is loading a csv file with few columns like email, name, city and I'm trying to send them daily updates via 2 smtp servers I have. I thought to use a backgroundworker because it's progress capabilities(for the progressbar I have) but I read also on this website that there are other alternatives like task, thread or threadpool.
I also read that sending emails must be done with an async method. I don't know if it's possible or if it's optimized for performance, but I'm trying to do the following:
for each smtp I wanna use a thread to read, let's say, 10 lines from the csv file,
split the line by fields and send the info to another thread which will send the message to each email in that small list. I wanna do this to save some precious time for each smtp auth procedure.
Because connecting to the smtp for each email requires the whole socket procedure everytime, like HELO, AUTH, DATA. If I'm gonna send a list of email, I can keep the socket open after auth and change only the data I send. 10 lines is just a variable which can be custom changed.
So, 2 tasks for each smtp, means 4 in total or can be increased based on the number of smtps I will use.
Can I also use additional threads for each task or backgroundworker?
I'm kinda confused because I'm new to c# and I haven't found any example about this. It's been more than a week since I'm trying to understand how backgroundworker/threads work but still unsuccessfully. Any help would be appreciated and any idea better than mine to improve the performance Thanks!
First off you need to understand the difference between the different types of threads.
A threadpool is just a collection of threads available for use. The threads used by the pool are managed by the pool & returned there after use. The idea is you get performance benefits because the cost of creating the thread only happens once.
A background worker is a thread that runs in the background. The only difference between a background and foreground thread, is a background thread will not prevent a process from terminating.
Sending emails async is more SHOULD rather than MUST. The smtp component has no concept of seperating the connect form the send.
I think what you want to do is:
initalise a number of threads, say 10.
Read a line from the csv.
Pass this line to a thread from above. If no threads are available, wait till one is.
In the thread parse the line and send the mail. Sending doesn't need to be async with this method but you can if you want. When you're done sending, return the thread to the pool ready for the next line
You can manage your threads as a pool - there are many examples around if you google for thread pools - or you can do it by hand using manualresetevents to handle the wait. The advantage of doing it with a pool is you can change the number of workers available easily without affecting your code.
All
I have an application that allows a user to communicate with multiple serial devices.
A manager class is used to start the application, which creates a new thread for each serial device. Inside this thread, the serial device is created and the thread and serial device object are stored inside the manager class for later when needed.
The serial device class then creates a com port class on it's own new thread which is used to connect to the com port and send / receive data. When data is received an event is fired up to the serial device class which in turn fires an event to the manager class, which in turn fires an event to the UI to alert the user that new data has arrived.
My problem comes that when the com port class fires it's event to notify the serial port class, the serial port class receives the event and continues processing under the com port thread. Likewise if the user sends any information down to the com port, it all runs under the UI thread.
I will add code as an edit later, but for now, if anyone can spot anything obvious I would be seriously greatful.
I have tried receiving the event in the serial device class and then invoking a method to see if that makes it run under the correct thread but that was no good.
I know the serial device thread is running as I do an Application.Run inside the class after it's created it's com port classes.
I'm not using any background workers as these threads are meant to exist for the life of the application and I understand background workers are meant to be used for short running calculations.
Many thanks
EDIT:
Forgot to mention, this is a Winforms app in .NET 2.0, so no Dispatcher available
EDIT:
Okay, so it looks like that the information is being passed up inside the DataReceived thread (I think as it isn't the com port thread either).
I also tried using a BackgroundWorker for the serial device class but this also didn't make any difference.
Help?
.NET 2.0 has SynchronizationContext. It's a slight pain (you have to pass the context from the UI thread to the others) but it should do the trick.
More info here: http://msdn.microsoft.com/en-us/magazine/gg598924.aspx
It sounds as if you need to create a kind of messaging mechanism to send messages from the UI thread to the correct port-thread. A queue might work. Let the UI thread post messages on the queue and have the port-thread process these messages.
Switching from the port-thread to the UI thread can be done using Dispatcher.CurrentDispatcher
Is this what you are looking for?
EDIT I am assuming a WinForms application