Async Task Timeout? - multithreading

There is a very common task I face again. I have already solved this a couple of times, but now I am looking for a more "elegant" way - can you deliver some input?
Situation:
I have a Method which I would like to run "semi async". In other words: Start it and wait a given time x. If the method is not finished by then ("timed out"), I want to continue my code with some cleanup procedures.
Solutions so far:
Use an AutoResetEvent (or
ManualResetEvent) combined with an
annonymus method using
.WaitOne(x).
Use a Thread/BackgroundWorker
combined with a Timer. If the timer
hits its handler before the thread stops it, the therad is timed out.
Both appraochs work fine but I imagine there is a better way with 4.0.
Suggestions?

Does Task.Wait(Timeout) from the Task Parallel Library do what you want? (You may wish to combine this with cancellation tokens to cancel the task after the timeout occurs.)

Related

How can I monitor stalled tasks?

I am running a Rust app with Tokio in prod. In the last version i had a bug, and some requests caused my code to go into an infinite loop.
What happened is while the task that got into the loop was stuck, all the other task continue to work well and processing requests, that happened until the number of stalling tasks was high enough to cause my program to be unresponsive.
My problem is took a lot of time to our monitoring systems to identify that something go wrong. For example, the task that answer to Kubernetes' health check works well and I wasn't able to identify that I have stalled tasks in my system.
So my question is if there's a way to identify and alert in such cases?
If i could find way to define timeout on task, and if it's not return to the scheduler after X seconds/millis to mark the task as stalled, that will be a good enough solution for me.
Using tracing might be an option here: following issue 2655 every tokio task should have a span. Alongside tracing-futures this means you should get a tracing event every time a task is entered or suspended (see this example), by adding the relevant data (e.g. task id / request id / ...) you should then be able to feed this information to an analysis tool in order to know:
that a task is blocked (was resumed then never suspended again)
if you add your own spans, that a "userland" span was never exited / closed, which might mean it's stuck in a non-blocking loop (which is also an issue though somewhat less so)
I think that's about the extent of it: as noted by issue 2510, tokio doesn't yet use the tracing information it generates and so provide no "built-in" introspection facilities.

Timer function queueing in Matlab

I have an issue with a timer function not always running as desired in Matlab.
I am trying to run an external simulation then fire a watcher function which checks the sim has exited correctly after a set time, if not it will force kill the task so it can be started again.
However the function works correctly for the first 2 batches of simulations then ceases to run. I am restarting the timer and using single shot. So each time the sim exits the timer is restarted. The timer callback is the function to kill the sim and the docs say 'Callback functions execute code during some event' which suggests the function should run regardless of any other matlab code. Is this correct or do callbacks work in some other way?
I initially thought this to be an issue with the execution queue holding the matlab worker for the sim, however it doesn't explain why it works for the first 100 or so times.
To be able to solve my issue I need more information on how the matlab workers work with regards to timer call backs. I am aware that unless specified matlab works on a single execution queue but I do not understand how callbacks function in this environment.
Any information regarding when and how timer call backs execute (ie do they fire exactly when timed to do so or do they simply get added to the queue at that time?) and any way of forcing a function to run regardless of the current worker would be greatly appreciated.
I have tried using batch() instead of a timer call back but the shell commands do not seem to work in a batch function (I have no idea why).
Many thanks

Should we use Task.Delay to replace Thread.Sleep

I am studying the new TPL to make my home made workflow work better.
Right now, I am entered into the maze of Task.Delay and Thread.Sleep. Acutally, Task.Delay(50).Wait() works just like Thread.Sleep(500). So which one should I use in my code?
from the many articles on internet, I have an impression that Task.Delay supports cancellation that Thread.Sleep does not support, so if I want to just block my thread for a duration without cancellation, will the use of Thread.Sleep be better than Task.Delay?
If you require cancellation, Task.Delay is an easy solution to that. I has overhead on top of Thread.Sleep: It constructs a timer and when you wait on this task you construct a wait handle that is signaled by the timer.
That said, you will only notice this overhead in tight loops (and sleep-throttled loops are rarely tight).
Use Thread.Sleep for blocking without cancellation. This is how it has always been done. It is well-known and idiomatic. Use Task.Delay(...).Wait(); for cancellation support.
You can do this in many other ways. For example, construct a SemaphoreSlim or TaskCompletionSource and wait for it using a CancellationToken. That's not as simple as Task.Delay, though.
Maybe Thread.Sleep, which may call Sleep() API directly, will be better than Task.Delay, which create Task object. Task.Deley requires more overhead and a bit more long code.
the easier code is, the better.

The main form stop responding

I wrote a function that does alot of mathematical operations and it takes about 10 minutes to finish its work. I tried to call this function via a button on a form (Windows forms application). But the problem now is during the 10 minutes, the main form stops to respond till the function is finishing its work.
How can i solve this... any idea!
You might assign a new thread for the calculations so that the form would not have to wait for the calculation to finish to continue execution (i.e. listening to and responding to events etc.)
The problem is that, while your 10 minute function is working, the rest of the program is not executed. In particular, it cannot execute the rendering. (i.e. making your form respond).
The solution is to use threads.
As already mentioned you should assign long running tasks to a worker thread or a threadpool thread.
Keep in mind that there are limited numbers of threadpool thread. ALso Windows forms is not thread safe so you should not be directly updating the form from the created thread. You can make use of InvokeRequired.
In this case better to use BackgroundWorker class. Details in following link.
http://stuff.seans.com/2009/05/21/net-basics-do-work-in-background-thread-to-keep-gui-responsive/

How to use TIMERS in vc++? I want to run different functions or code after a definite time interval(say 10 ms) without using Sleep()

Hi all i want to execute code similar to a Interrupt service routine after a timer expires(say print hello after every 10ms) and this is a supplementary activity so it has to be using a timer .So how do i implement timers in vc++
You want to use the CreateTimerQueueTimer() function. Here is the MSDN sample code.
If you need something that runs on older platforms you're stuck with SetTimer(), which delivers a WM_TIMER message to your WNDPROC. It's a pretty terrible API, so I'd really recommend using the Timer Queue function.
CreateTimerQueueTimer() will spawn a worker thread which does the work of figuring out how much time has elapsed and then call you back when it pops. There are threading implications, but it is much nicer overall, especially if you don't want to have a Window.
Use SetTimer to setup a timer with specified time out. You can either specify a callback method in SetTimer or handle WM_TIMER message. Once done use KillTimer to kill the timer. See this example in MSDN.

Resources