public static T AwaitAsyncTyped <T>(IScriptCallContext context, Tasks.IAsyncResult <T> result) { if (!result.IsCompleted) { result.AsyncWaitHandle.WaitOne(); } return(result.Result); }
public static T AwaitAsyncToTyped <T>(IScriptCallContext context, Tasks.IAsyncResult <object> result) { if (result != null && !result.IsCompleted) { if (!result.AsyncWaitHandle.WaitOne(20000)) // TODO: Register this "task" and replace with loop that waits a short while. { throw new TimeoutException($"Timeout waiting for asynchronous result in line {context.CurrentScriptFileLine}."); } } if (result.IsFaulted) { if (result is IObjectFaultDescriptor) { context.ReportError("Async operation failed. Fault: " + ((IObjectFaultDescriptor)result).FaultDescription); } else { context.ReportError("Async operation failed."); } return(default(T)); } else { object v = result?.Result; if (v != null) { var valueType = v.GetType(); if (typeof(T).IsAssignableFrom(valueType)) { return((T)v); } else if (valueType == typeof(string)) { try { object value = Convert.ChangeType(v, typeof(T)); return((T)value); } catch { } } throw new InvalidCastException($"The async result value type is \"{v.GetType().TypeName()}\", and cannot be converted into a \"{typeof(T).TypeName()}\"."); } } return(default(T)); }