Task async/await support for scheduled jobs
The scheduled jobs are executed as tasks by the scheduled job executor (IScheduledJobExecutor. However the Execute method that is required to create and run a custom job does not support return type Task or Task<T> and therefore the async/await syntax cannot be used. When performing expensive procedures such as reading files or executing web requests the thread is kept busy as a result. Also as far as I'm aware if I need to call an async function/method in the job then a workaround has to be used. An example of how others do this can be seen in this forum post:
https://world.optimizely.com/forum/developer-forum/CMS/Thread-Container/2019/5/safe-way-to-call-async-method-in-episerver-scheduled-job/
The benefit of using a Task as the Execute return value is that the usage of async/await will free up the thread so that it can be used for other purposes. It currently does not seem possible implement await, or return to the caller, while calling an asynchronous function within a job. Because of this it's required to wait for the result of that function synchronously. In some cases developers might use Task.Run or StartNew purely to execute asynchronous functionality in a synchronous fashion. That can result in another thread unnecessarily being used to run the new task (correct me if I'm wrong.
As a change request and possible solution, please add support for a Task/Task<T> Execute(CancellationToken token method that is invoked and awaited by the job executor. The async/await syntax can then be used to handle asynchronous implementations more easily and will potentially result in less resources being used by the threadpool. I'm sure the final solution will be more complex than the above but hopefully this can still be a minor change.
-
Sammy Ender
commented
The inability to call an async function using "await" has a huge pain point for us. We do API calls in pretty much every job we have that runs daily which is many. We have definitely had issues when doing ".GetAwaiter().GetResult()" for our API calls or when trying to multi-thread in order to reduce job execution. This should absolutely be added as a feature to CMS 13