diff --git a/LiamExchange/C4IT.LIAM.ExchangeManager.cs b/LiamExchange/C4IT.LIAM.ExchangeManager.cs index 3929015..34a0747 100644 --- a/LiamExchange/C4IT.LIAM.ExchangeManager.cs +++ b/LiamExchange/C4IT.LIAM.ExchangeManager.cs @@ -62,32 +62,24 @@ namespace C4IT.LIAM var runspace = RunspaceFactory.CreateRunspace(connectionInfo); LogEntry($"Opening Exchange runspace (timeout: {RunspaceOpenTimeout.TotalSeconds:0}s) for endpoint '{_exchangeUri}'", LogLevels.Debug); - IAsyncResult openResult = null; - try + var openTask = Task.Run(() => runspace.Open()); + if (!openTask.Wait(RunspaceOpenTimeout)) { - openResult = runspace.BeginOpen(null, null); - if (!openResult.AsyncWaitHandle.WaitOne(RunspaceOpenTimeout)) + try { - try - { - runspace.Dispose(); - } - catch (Exception disposeEx) - { - LogException(disposeEx); - } - - throw new TimeoutException( - $"Timeout while opening Exchange runspace after {RunspaceOpenTimeout.TotalSeconds:0} seconds."); + runspace.Dispose(); + } + catch (Exception disposeEx) + { + LogException(disposeEx); } - runspace.EndOpen(openResult); - } - finally - { - openResult?.AsyncWaitHandle?.Close(); + throw new TimeoutException( + $"Timeout while opening Exchange runspace after {RunspaceOpenTimeout.TotalSeconds:0} seconds."); } + openTask.GetAwaiter().GetResult(); + LogEntry("Exchange runspace opened successfully", LogLevels.Debug); return runspace; } diff --git a/LiamExchange/ExchangeManager.Extensions.cs b/LiamExchange/ExchangeManager.Extensions.cs index 5d7ba8b..7e4aa42 100644 --- a/LiamExchange/ExchangeManager.Extensions.cs +++ b/LiamExchange/ExchangeManager.Extensions.cs @@ -19,7 +19,7 @@ namespace C4IT.LIAM { private static readonly TimeSpan PowerShellInvokeTimeout = TimeSpan.FromSeconds(120); - private static Collection InvokePowerShellWithTimeout(PowerShell ps, TimeSpan timeout, string operationName) + private static PSDataCollection InvokePowerShellWithTimeout(PowerShell ps, TimeSpan timeout, string operationName) { IAsyncResult asyncResult = null; try