c# - Polling the right way? -
I'm software / hardware engineer with some experience in C and embedded technologies, and currently I'm doing something in C # (.NET)
I'm busy writing apps which are using hardware for data acquisition. Now the following, burning for me, question:
For example: I have a machine in which there is one end to find the last place of a pivot. Now I am using the USB Data Acquisition module to read data. Currently I am using a thread to read port-states continuously.
There is no interruption on this device.
My question: Is this the right way? Should I Use Timers, Threads or Tasks? I know that there is something in the poll that most of you "hate", but any suggestions are welcome!
IMO It depends very heavily on your exact environment, but before that: in most cases you have threads Should not be used
- Low voting interval: Timer and voting in
tick
. Work - Medium: Waiting for
Tasks
andTasks Delay (delay)
- High: Using
tasks
andthreads. Sleep (delay)
Why "Less Solution": Timer is easy to handle and easy to stop; there is no need to worry about the thread / functions running in the background , But the main thread is holding in.
Why "Medium Solution": Waiting for the job. Delay (delay)
does not block the thread-pool thread, but due to the reference to the minimum delay, ~ 15m.
On "1ms delay" the "high resolution" is usable - we actually do here to choose our USB measurement device.
It can be implemented as:
int delay = 1; Var cancellation tokens = new cancellation (); Var Token = Cancellation Token. Source; Var listener = Task. Factor STARTNU (() = & gt; {while (true) {// pole hw thread sleep (delay); if (token ic cancellation request) brake;} // cleanup} token, task selection option, task scheduler default ); In most cases you can only use
should be enabled, but does not apply here). Especially "stop" just code in from anywhere to this Cancellation of the codeTasks.Run ((=) => DoWork (), Token
, butTask Action Option. Anchor option
which tells the task-scheduler not to use the normal thread-pool thread.
But as you can see it is easy to handletasks
(and < Code>) You can also share this token in many tasks and can stop them once. Work has not been started even then.
You can also attach another task to a task after a task:
listener .continueWith (t => shutdown (t));
This is executed after the completion of the listener and you do the cleaning (
t.exception
is an exception to the functioning tasks if it does not succeed).
Comments
Post a Comment