Introduce TimeSpan extensions

This commit is contained in:
softworkz
2025-12-07 11:20:43 +01:00
parent 2b2b26e13b
commit c97f914e7a
14 changed files with 154 additions and 68 deletions

View File

@@ -31,7 +31,7 @@ namespace ElectronNET.API
CamelCase,
}
private const int InvocationTimeout = 1000;
private static readonly TimeSpan InvocationTimeout = 1000.ms();
private readonly string objectName;
private readonly ConcurrentDictionary<string, Invocator> invocators;
@@ -120,7 +120,7 @@ namespace ElectronNET.API
return this.InvokeAsyncWithTimeout<T>(InvocationTimeout, arg, callerName);
}
protected Task<T> InvokeAsyncWithTimeout<T>(int invocationTimeout, object arg = null, [CallerMemberName] string callerName = null)
protected Task<T> InvokeAsyncWithTimeout<T>(TimeSpan invocationTimeout, object arg = null, [CallerMemberName] string callerName = null)
{
Debug.Assert(callerName != null, nameof(callerName) + " != null");
@@ -245,7 +245,7 @@ namespace ElectronNET.API
private readonly Task<T> tcsTask;
private TaskCompletionSource<T> tcs;
public Invocator(ApiBase apiBase, string callerName, int timeoutMs, object arg = null)
public Invocator(ApiBase apiBase, string callerName, TimeSpan timeout, object arg = null)
{
this.tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
this.tcsTask = this.tcs.Task;
@@ -306,7 +306,7 @@ namespace ElectronNET.API
_ = apiBase.Id >= 0 ? BridgeConnector.Socket.Emit(messageName, apiBase.Id) : BridgeConnector.Socket.Emit(messageName);
}
System.Threading.Tasks.Task.Delay(timeoutMs).ContinueWith(_ =>
System.Threading.Tasks.Task.Delay(timeout).ContinueWith(_ =>
{
if (this.tcs != null)
{
@@ -314,7 +314,7 @@ namespace ElectronNET.API
{
if (this.tcs != null)
{
var ex = new TimeoutException($"No response after {timeoutMs:D}ms trying to retrieve value {apiBase.objectName}.{callerName}()");
var ex = new TimeoutException($"No response after {timeout:D}ms trying to retrieve value {apiBase.objectName}.{callerName}()");
this.tcs.TrySetException(ex);
this.tcs = null;
}

View File

@@ -1,6 +1,7 @@
using ElectronNET.API.Entities;
using System;
using System.Threading.Tasks;
using ElectronNET.API.Entities;
using ElectronNET.Common;
// ReSharper disable InconsistentNaming
@@ -173,7 +174,7 @@ public class WebContents : ApiBase
/// Get system printers.
/// </summary>
/// <returns>printers</returns>
public Task<PrinterInfo[]> GetPrintersAsync() => this.InvokeAsyncWithTimeout<PrinterInfo[]>(8_000);
public Task<PrinterInfo[]> GetPrintersAsync() => this.InvokeAsyncWithTimeout<PrinterInfo[]>(8.seconds());
/// <summary>
/// Prints window's web page.
@@ -388,7 +389,7 @@ public class WebContents : ApiBase
/// Returns string - The user agent for this web page.
/// </summary>
/// <returns></returns>
public Task<string> GetUserAgentAsync() => InvokeAsyncWithTimeout<string>(3000);
public Task<string> GetUserAgentAsync() => InvokeAsyncWithTimeout<string>(3.seconds());
/// <summary>
/// Overrides the user agent for this web page.