Does Electron Provide Built‑In Timeout Support for ipc.invoke?
0 reputation · 22 Jul 2024, 15:00 UTC
0 reputation · 22 Jul 2024, 15:00 UTC
Gracefully cancel or timeout IPC calls and page loads in Electron.
Electron’s promise‑based IPC has no timeout argument; developers must wrap calls in Promise.race. The underlying handler continues to run, potentially wasting CPU or I/O. Navigation events can be prevented with event.preventDefault(), but there is no generic timeout for page loads.
An open issue proposes adding an optional timeout parameter to ipc.invoke, but no merge has occurred in the latest stable releases.
What is the current status of built‑in timeout support for ipc.invoke, and how can developers best avoid resource waste when using Promise.race to simulate timeouts?
34775 reputation · 22 Jul 2024, 18:23 UTC
Electron does not provide a built‑in timeout argument for ipc.invoke. The method returns a plain Promise that resolves or rejects only when the handler finishes.
ipc.invoke API signature is invoke(channel, ...args) with no optional timeout parameter.Promise.race with a timer Promise will reject the caller’s side after the timeout, but the original handler continues to run in its process.Because Electron’s IPC is designed to be fire‑and‑forget on the sender side, adding a timeout would require a cancellation mechanism on the receiver side, which does not exist today. The race‑only approach therefore leaves the handler to finish its work, potentially wasting CPU, I/O, or blocking threads.
AbortController in the renderer and pass its signal to the handler via an extra argument or a shared message.signal.aborted and return early or throw to stop further work.Worker thread or a separate child process so that terminating the worker frees resources.catch branch of the Promise.race, ensure any allocated resources (e.g., file handles, timers) are released.Can you modify the IPC handler (the main‑process function that receives the ipc.invoke call) to check for an abort signal? If yes, the AbortController pattern above is the recommended approach; if not, you must rely on offloading to a worker and terminating that worker when the timeout occurs.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.