My program collects data from various sensors and whenever there is something wrong with the sensor reading, then I have to send an email to alert the user.
For this, I have assigned a variable SEND_MSG to trigger the email send event. Whenever there is something off with the reading, I set SEND_MSG to 999 and another thread, which loops and checks this variable triggers the send email process. Read/Write operation of the SEND_MSG occurs inside a lock statement.
Is there a better way to do this?
Thank you.
You are polling a variable holding status from a thread to communicate state. That's not a very efficient design.
There are a number of inter-thread communication mechanisms that handle this situation much more elegantly.
For a great overview of mechanisms see http://www.albahari.com/threading/
If you simply want to communicate the need to send an email, you can use for example an AutoResetEvent.
Another option, which makes it easy to communicate additional information such as the sensor number, type of malfunction, etc., you can consider using a BlockingCollection. There's a good example of how to use it at the bottom of that link.
Related
I have an application running an infinite loop and performing some important functions in that loop. I need to provide the user with another application which would terminate the application with infinite loop. The problem is what if the user terminates the application when it is inside loop performing some operation. It would lead to inconsistent state. I tried kill() and TerminateProcess but they didn't help. Is there any way I could signal the application with infinite loop that complete your iteration and exit? I am open to solutions in c#,cpp and vc++.
EDIT:
The source code for looping program is accessible.
While there are many variations on Interprocess Communication, for this purpose a simple event will suffice.
In the process you need to control:
hEvent = CreateEvent() (with a name, make it sufficiently unique)
Periodically check it with WaitForSingleObject(hEvent, ZERO_TIMEOUT)
From the process to do the controlling:
hEvent = OpenEvent() passing the same name
SetEvent(hEvent) will cause the return value from WaitForSingleObject in the other process to change.
A slightly nicer way might be to start a background thread in the main application which creates a window and a taskbar icon with an Exit option on its menu. Then you only need to share an event between threads, not between processes, which removes the requirement for a unique name.
an application running an infinite loop and performing some important functions
As long as it does "important functions", the program in question has a way to obtain new input data from somewhere (e.g., from a file or from a network socket). Therefore, you can add a special token into input data with a meaning "end of operation". Upon receiving such token, the program will know that it is time to shut itself down. One of the simplest tokens of such nature are end-of-file for regular files or remote side socket closure.
The method I just described is simple and is what may be called "in-band control channel". That is, you use a single channel to both feed data to process and commands to control (even if there is just one command, "stop").
An alternative to that would be "out of band control channel", that is, a second channel to pass commands between applications.
The problem is what if the user terminates the application when it is inside loop performing some operation. It would lead to inconsistent state.
Your attempts to use kill is one possibility to use facilities known as inter-process signals. To use it properly, the receiving program must register a signal handler routine to initiate a shutdown on its own. The sender should use a matching signal number. Using kill (SIGKILL in POSIX) is not the best choice because it has a special behavior and cannot be assigned with a custom signal handler. In POSIX, it is better to use SIGUSR1 or one of many other signals. I do not remember native Windows equivalents for that.
There is a multitude of mechanisms to organize an inter-processor communication between processes in a conventional operating system, see Wikipedia to a full list for everything from a shared file to named pipes and network sockets. Choose one that suites your needs best. You only need to pass a single bit of data, so basically the one that is the easiest to program is the best.
I have read dozens of articles about threading in c# and Application.DoEvents() ... Still can't use it properly to get my task done:
I have a controller connected to my COM, this controller works on command (i send command, need to wait few ms to get response from it), assume the response is a data that i want to plot every time interval using a loop:
start my loop.
send command to controller via serialPort.
wait for response (wait let say 20 ms).
obtain data.
repeat this loop every let say 100 ms.
this simply doesn't want to work!! i tried to communicate with the data controller on other thread but it seems that it can't access the serialPort which belongs to the main thread (roughly speaking).
any help is appreciated
Application.DoEvents is for all it does - nothing more than a nested call to a windows (low level) message loop on the same thread. Which might easily cause recursion if you call it in in an event handler. You might consider creating your serial port object on the worker thread and communicate through threading classes (i.e. the WaitHandles and similar). Or call back to your UI thread using "BeginInvoke" and "EndInvoke" on the UI object.
If you catch the SerialPort.DataReceived event and then use wither SerialPort.ReadLine or SerialPort.Read(byte[],int,int) those methods will be executed on a new thread. I prefer to use a mutex to control access to the buffer of bytes as a shared resource. Also have you ever communicated with your device successfully? If not in addition to the port setting check the SerialPort.NewLine property and the SerialPort.Handshake property. These settings vary depending on the device you are trying to communicate with.
Why do you use it to begin with?
Have a look at this pages, it might give you a direction
My favorite: Is DoEvents Evil?
From msdn blog Keeping your UI Responsive and the Dangers of Application.DoEvents
From msdn forums Application does not return from call to DoEvents
Without code, it'll be hard to help. Even with code, it might be hard to help :)
I'm agreeing with gunr2171 on this :)
First of all, I wanted to thank the community. You've been of great support lately ! Usually i don't even need to ask the questions because they're already there. Now i have an issue that's not directly related to code but programming itself.
I'm working with a FTDI Chip and C# programming a communication protocol in which a PC application acts like the Master (will send requests) and there is also Slave device who will answer to them, not immediately, maybe a couple of millisecs, but anyway, will take some time. I'm stuck in a conceptual/philosophical code design question.
After sending a request, should I ask right away for an answer (checking also a timeout) or should I constantly monitor the input (BackgroundWorker powered) and raise an event after receiving a data input ? What would you recommend, what is on your experience. What factors should i consider for making my choice ?
I never studied software design of programming itself so i think i lack the basic on this, but this is a personal project i'm working on and sure i'd love some feedback/pointers on this from you guys.
Thanks !
My preferred solution in this scenario would be to issue the request in async mode (such that you get called back by an event that fires when it completes), and also implement an async time out using standard .Net mechanisms, which calls you back if it appears the slave is unresponsive. This way you just start the request and the timer and then can continue doing more work, without needing any other threads to process results.
You would have to make sure that concurrent time out and response arrival is handled cleanly using a locking mechanism, so that you know for sure whether you are timing out or handling the response.
Try to avoid polling and input monitoring, unless your slave's API does not allow for deterministic generation of response events.
Normally i would work with the asynchronous approach on the low level site and maybe put some synchronization mechanism on top of this. Here is some example approach if you get data fragments and you have to put these fragments together to a whole message.
So on the low level site implement a BackgroundWorker that checks constantly for incoming data and raise some kind of event if you got something and put this into the event.
Above this is someone listening to the events of incoming data and puts all this (maybe) fragments into an internal queue. There it checks if it already has a enough data for a complete message, maybe does some error checking, etc. If it has a complete message it will raise an event to send this message to all listeners out there.
On top of this put another class that watches for messages and reacts on them. This class maybe implements some sync mechanism to watch out if an incoming message matches to something that should happened beforehand.
I think this design makes it easier to react on data that comes in when you don't expect something. And when you like to shutdown you don't have to wait for any timeouts to happen (maybe a very small one the low level BackgroundWorker is using to pull the data out of the source that doesn't support an event mechanism).
I am trying to make an app that will pass data between two servers Connection1 and Conenction2 using sockets.What i would like to do is receive data from Connection1 and pass it to Connection2 and vice-versa.Connection1 and Conenction2 are on different threads. What is the best way to call methods on different threads in order to pass data back and forth between them.Both threads will use the same message object type to communicate in both directions between them.
Thanks
You should use immutable data transfer objects.
As long as a simple object is deeply immutable (meaning that neither it nor any of it's properties can change), there is nothing wrong with using it on multiple threads.
To pass the instances between threads, you might want to use a pseudo-mutable thread-safe stack. (This depends on your design)
If .NET 4 is an option, I'd strongly recommend having a look at the ConcurrentQueue<T> and possibly even wrapping it with a BlockingCollection<T> if that suits your needs.
That depends on what those threads are doing. While passing data between threads is relatively straight forward, waking the threads to process the data can be more tricky. When you design communication with a thread per/connection paradigm, your thread is almost all the time stuck in a Read method, like Socket.Receive. While in this state, other threads cannot actually wake this thread to have him send the data they want it sent. One solution is to have the Receive time out every second and check if it has data to transmit, but that just plain sucks.
Another idea is to have 2 threads per socket, one to Send one to Receive. But then all the advantages of having a thread per socket are gone: you are no longer able to have a simple state management of the 'session' in the thread code, you have a state shared between two threads and it's just a mess.
You can consider using async Receive instead: the socket thread posts a BeginReceive then waits on an event. The event is signaled by either the Receive completion or by the send queue having something 'dropped' in (or you can wait on multiple events, same thing basically). Now this would work, but at this moment you have a half-breed, part async part one-thread -per-socket. If you go down this path, I'd go the whole 9 yards: make the server fully async.
Going fully async would be the best solution. Instead of exchanging data between threads, completion routines operate on locked data. The Connection1 BeginReceive completes when it receives data, you parse the received data and analyze the content, then decide to send it on Connection2. So you invoke BeginSend on Connection2's socket, meaning the thread that received the data also send the data. This is much more efficient ans scales better than the thread-per-socket model, but the big disadvantage is that is just plain complicated if you're mot familiar with async and multithreaded programming.
See Asynchronous Server Socket Example and Asynchronous Client Socket Example for a primer.
What you are describing as asynchronous messaging. Microsoft has already written an app for this called MSMQ
I would use WCF on .NET 3.5 for this task, it will be more scalable. I'm using WCF for a lot of my works and its flawless. The good thing about it is you can share your data across any platform.
http://msdn.microsoft.com/en-us/netframework/aa663324.aspx
I was writing up a long, detailed question, but just scrapped it in favor of a simpler question that I didn't find an answer to here.
Brief app description:
I have a WPF app that spawns several threads, and each thread executes its own WF. What are some of the best ways to handle errors in the threads and WF that will allow user interaction from the GUI side? I definitely plan to handle any low level exceptions in the thread, because I don't want the thread to exit.
Summary of questions:
How have you implemented communication between WF and the thread that starts it? There is WorkflowTerminated, but I don't want the workflow to exit -- I need to fix the problem and let it continue. I assume the only option is using a FaultHandler, but was wondering if there's another way to do it without using an activity block. I am hoping there's a framework out there that I just haven't found yet.
The error from WF needs to get caught by the thread, which then needs to display the error in the GUI. The user will then make a logical choice for recovery, which should then be sent back to the thread, and then to WF. Again, is there something existing out there that I should take a look at?
Even buzzwords / keywords that accomplish what I am describing would be really helpful, and I can do the legwork on researching each of them. However, any additional insight is always welcome. :)
What's worked for me in multi-threaded WPF apps is to have the errant thread invoke a callback method that passes the exception and other info back to the UI thread. Callbacks can have return values, so if your thread can block while waiting for the user to respond, then that can work for you. Remember that the callback will run on the thread that calls it, so any UI updates have to be done via the control's dispatcher. You will have to decide whether all of the threads use the same callback and what kind of synchronization you'll need if there's a chance that multiple threads can throw exceptions simultaneously.
Here's how I ended up solving this problem. But first a little background info:
User clicks a button in the GUI that causes the candy packager to start running. This is done via a command binding in the ViewModel, which then calls a low-level function in the Model. The function in the model launches a thread and executes a state machine.
At some point, the machine will fail. When it does, I compile information about the error and possible (known) recovery methods. I put this into an object and then pass it to the GUI via a callback interface. In the meantime, the worker thread is stuck waiting for an Event to get set.
Eventually, the candy worker will notice the error and will click a button telling the system what to do. This results in two things: 1) it flags one of the recovery methods as the preferred one, and 2) sets the event. Now the worker thread continues on, checks for the preferred error recovery method and transitions into the respective state in the state machine.
This works very well (so far). The part I know is totally lame is the manner in which it checks for the preferred error recovery method. I am essentially setting a string variable, and then comparing this string to a list of known strings. Ultra lame, but I'm not sure of a better way to do this, other than using an enum. Does anyone have recommendations for me?