In .NET Fx 4 we used to use this approach described here to timeout a method call. This approach relies on Thread.Abort()
that doesn't work in .NET 5 as explained here "It may come as a surprise that Thread.Abort was never implemented for .NET Core".
What is super useful in this approach is that the called method (the one that might timeout) is executed on the main thread, the same thread used to execute the caller method that initiates the call. Before this call, an async thread is fired to wait during the timeout interval and then eventually call Thread.Abort()
on the main thread that catches ThreadAbortException
and then in the catch handler calls Thread.ResetAbort()
.
How can we have the same behavior with some .NET Core / .NET 5 code?
This Microsoft doc Cancel async tasks after a period of time shows something different where the method that can timeout is called on an async thread and not on the main thread.