Why is SEH considered "asynchronous"? - windows

A few of the articles / answers I read on SEH (Structured Exception Handling) consider it to be 'asynchronous'.
It is my understanding that the whole handling part of these exceptions occurs on the thread that raised them (on the CPU level). Basically, once an exception occurs, the excecution 'jumps' to OS code that iterates on the current thread exception handler list.
So is my understanding correct? What exactly is asynchronous about SEH?

In the synchronous model of exception handling, exceptions are always explicitly thrown; an actual throw statement has to occur in the source code, at a known and clearly defined point in the instruction stream so the compiler has knowledge of when exceptions can occur (which also means it can optimize out exception handling code if it can prove no exceptions can occur).
SEH is about CPU triggered exceptions, things that the code itself didn't realize could happen, but were raised "out of band" so to speak. It's asynchronous in that the exception is injected into code that was unaware it could even happen, much in the same way signal handlers can be run in the main thread, interrupting whatever was actually happening at the time the signal was received.
SEH can be thought of much like temporarily registered signal handlers, where the exceptional conditions are signals, the __try blocks define where the handler is in effect, and the __except and __finally blocks are the handlers if the "signal" is received.

Related

What exceptions in asp.net 5 could/should be considered as "permanent" vs. "non permanent"?

If an Eventhandler that updates a projection in the read model throws an exception, this is a bad thing.
In this case I would like do differentiate between "permanent" and "non permanent" exceptions.
With "permanent" Exceptions I mean Exceptions, that most likely are caused by wrong code and will be thrown again and again if I try to retry handling the event on this event handler.
With "non permanent" Exceptions I mean "temporary" e.g. Io/Network/... related Exceptions that are not caused by wrong code and which make sense to retry until the event is eventually handled successfully.
While I can come up with examples I would consider the one or the other (like InvalidOperation or IOException) is there any list or recommendation which exception (in this case in the asp.net 5 stack) should be considered what?
One option is to add a retry or circuit breaker policy using Polly that automatically retries all the exceptions (per read-model) and after X retries, do either disable the specific read projection that failed or the entire read-model.
The question is what you want to happen when the read model can't be updated. Do you:
Shut down the specific projection and allow the rest to be updated?
Shut down the entire read model
Or enter a "I am out of sync" mode?
I think this all depends on how you have constructed your read model and what your business case is.

How to trigger the execution of the compensation flow for the activities used within an Automatonymous state machine?

My activities throw exceptions from time to time during the execution, so I've implemented the Faulted methods of Activity<TInstance> to handle that, discarding the changes made in the Execute method. I thought that there's some wiring underneath in Automatonymous that makes it so that the Faulted method executes when the Execute method throws an exception and then calls the Faulted methods for the activities that were executed already. It turns out that there's no such thing, as my Faulted methods are never executed.
Should I call those myself in a try/catch block instead? I could produce the BehaviorExceptionContextProxy based on BehaviorContext and the exception thrown. The only next Behavior I could pass would be the one inserted into that Activity's Execute method, but logically that means I'm compensating in the wrong direction as that next Behavior is actually to be executed after this one succeeds, so I'd compensate too much.
I also tried to use the Catch in the state machine, which does handle the exception, however, I couldn't find any way to start the execution of the compensation flow for the activity that failed when I only have the ExceptionActivityBinder present.
Is there any good way to trigger the compensation flow of the activities?
An activity within a state machine (using Automatonymous) is much different than an activity within Courier. Unfortunately, they both have the same name, which can create confusion.
When an activity throws an exception, the Faulted method of the next activity in the behavior is called. If that method is a regular activity method (such as .Then, .Publish, etc.) it is skipped, since the Faulted method of those activities just calls the next activity in the behavior.
A Catch activity, however, can be used to catch the exception and execute a rescue behavior (which is a sequence of activities).
Either way, the Faulted method of the activity which throws an exception within the Execute method is not called. So yes, you should use a try/catch, but allow the exception to flow back out of the Execute method so that the behavior handles it properly.

How to attach uncaught exception handler/completion to CompletableFuture chain

The use-case:
an exception occurs during CompletableFuture chain
none of exceptionally, whenComplete or handle method is attached to that CompletableFuture chain
The result:
The exception is never caught and there's no tracking/log of it. Which in case of Async systems is 1) undesirable and 2) an indicator for hard and hidden problems (such as NPE, Runtime Exc, etc.) to spot.
The question:
Is it feasible to implement CompletableFuture.UncaughtExceptionHandler mechanism by analogy / in a similar manner with java.lang.Thread.UncaughtExceptionHandler? The idea is to provide [default] uncaught exception handler/completion to be called if the CompletableFuture chain does not have java.util.concurrent.CompletableFuture.UniExceptionally Completion attached.
The simple answer is: no.
However, someone posted an ugly hack to get similar behavior in another thread:
How to handle uncaught exceptions from CompletableFuture.runAsync
I for one escape this problem by using ReactiveX (http://reactivex.io), but that choice might be beyond your control. In that case, you could consider creating a wrapped class for CompletableFuture that always registers an exception handler behind the scenes, so you don't have to explicitely call exceptionally(..) any more. But again, this is just a work-around.

What happens when an async_write() operation never ends and there is a strand involved?

I know that the next async_write()'s should be performed when the previous one finished (with or without errors, but when it finished).
I would like to know what happens when, while making async_write() calls, if one of these takes long time for some reason or even never ends (I assume there is no timeouts here like in synchronous operations). When this operation will be considered as failed? When that operation that never ends is finally removed by the OS internally?
Maybe, are there timeouts involved and my assumptions are wrong?
I mean, the write operation is sent to the OS and could possibly block, indefinitely?
So the handler is never called and the next async_write()'s are never called.
NOTE: I am assuming that we are calling run() in several threads but the write operations should be sent in order so I am also assuming that the write handlers are wrapped with a strand.
Thank you for your time.
There are no explicit timeouts for asynchronous operations, but they can be cancelled through the IO object's cancel() member function. These operations will be considered as having failed only when the underlying OS call itself fails in a manner where a retry cannot reasonable occur. For example, if the write fails from:
EINTR, then the write will immediately be reattempted.
EWOULDBLOCK, EAGAIN, or ERROR_RETRY, then Boost.Asio will push the operation back into the job queue. This could occur if the write buffer was full, so pushing the operation back into the queue defers its reattempt, allowing other operations to be attempted.
Other errors will cause the operation to fail.
There should not be an indefinitely block in the system call. Boost.Asio sets the underlying IO objects to non-blocking, and provides synchronous blocking writes behavior by waiting on the associated file descriptor if a write failed with EWOULDBLOCK, EAGAIN, or ERROR_RETRY.
A strand is not affected by long term asynchronous operations. Strands are used to provide strict sequential invocation of handlers, not the operations themselves. In the case of composed operations, such as boost::asio::async_write, the intermediate handlers will also be invoked through the same strand as the final handler. Overall, this behavior helps provide thread safety, as:
All async_write_some operations initiated from intermediate handlers are within the strand.
The operation itself is not within the strand. This allows other for other handlers to run while the actual write is occurring.
The user handler will be invoked within the strand.
This answer may provide some more insight into composed operations and strands.

Waiting for task throws

I'm just starting out with WinRT's concurrency model. I have a task that I need to wait on, but calling wait() throws an exception that I can't catch.
Simplest possible code:
concurrency::task<StorageFile^> getFileTask = concurrency::create_task(Windows::Storage::ApplicationData::Current->LocalFolder->GetFileAsync(fileString));
getFileTask.wait();
The exception it throws is:
Microsoft C++ exception: Concurrency::invalid_operation at memory location 0x0402C45C
How do I set this up so that it works?
One of the most important rules that you must follow when building a Windows Store app is that you must never block the UI thread. Never ever.
If you start an asynchronous operation, you get a future or task that "owns" that operation. If you call get() or wait() on that operation before the asynchronous operation has completed, that call will block until the operation completes, then it will return the result.
Since blocking the UI thread is bad, if you attempt to synchronize with a not-yet-completed asynchronous operation on the UI thread, the call to get() or wait() will throw, to prevent the UI thread from being blocked. This exception is there to help you to remember not to block the UI thread. :-)
You should use task's then() to provide a continuation that will run when the asynchronous operation completes. If the continuation needs to run on the UI thread as well, be sure to pass task_continuation_context::use_current() to then() to ensure that the continuation is marshaled back to the UI thread for execution.
Note: This exception is only thrown if you are using C++/CX. If you are using C++ without the C++/CX language extensions, the call to get() or wait() will successfully block, potentially resulting in a poor user experience. In general, C++/CX has many more "guard rail" features like this one that are designed to make it easier for you to write good code. When using C++/CX, you get the full power of C++, with the understanding that there are more opportunities for error.

Resources