private static Task<Result> CreateCallbackTask(this IInstance instance, Callbacks callback, Func<Result> workUnit, Action<InstanceCallbackHandler> addHandlerAction) { instance.AddCallbackHandlerIfNeeded(callback, addHandlerAction); switch (callback) { case Callbacks.ObjectResult: return CreateCallbackObjectReferenceCounterTask(instance, workUnit); default: return CreateCallbackWorkItemQueueTask(instance, callback, workUnit); } }
private static void AddCallbackHandlerIfNeeded(this IInstance instance, Callbacks callback, Action<InstanceCallbackHandler> addHandlerAction) { if(!_CallbackWorkItemQueues.ContainsKey(instance) && !_CallbackObjectReferenceCounters.ContainsKey(instance)) { instance.Disposing += HandleInstanceDisposing; } switch(callback) { case Callbacks.ObjectResult: AddCallbackObjectReferenceCounterHandler(instance, addHandlerAction); break; default: AddCallbackWorkItemQueueHandler(instance, callback, addHandlerAction); break; } }
public OssiferWebView() { OssiferSession.Initialize (); CreateNativeObject (new string[0], new GLib.Value[0]); callbacks = new Callbacks () { MimeTypePolicyDecisionRequested = new MimeTypePolicyDecisionRequestedCallback (HandleMimeTypePolicyDecisionRequested), NavigationPolicyDecisionRequested = new NavigationPolicyDecisionRequestedCallback (HandleNavigationPolicyDecisionRequested), DownloadRequested = new DownloadRequestedCallback (HandleDownloadRequested), ResourceRequestStarting = new ResourceRequestStartingCallback (HandleResourceRequestStarting), LoadStatusChanged = new LoadStatusChangedCallback (HandleLoadStatusChanged), DownloadStatusChanged = new DownloadStatusChangedCallback (HandleDownloadStatusChanged) }; ossifer_web_view_set_callbacks (Handle, callbacks); }
private static Task<Result> CreateCallbackWorkItemQueueTask(IInstance instance, Callbacks callback, Func<Result> workUnit) { var callbackWorkItemQueue = _CallbackWorkItemQueues[instance][callback]; var taskCompletionSource = new TaskCompletionSource<Result>(); var callbackWorkItem = new CallbackWorkItem { TaskCompletionSource = taskCompletionSource, WorkUnit = workUnit }; callbackWorkItemQueue.Enqueue(callbackWorkItem); if (callbackWorkItemQueue.Count <= 1 && !TryExecuteWorkUnit(taskCompletionSource, workUnit)) { callbackWorkItemQueue.Dequeue(); } return taskCompletionSource.Task; }
public bool AddCallback(TaskCompletionSource <IObjectPrx?> cb) { Callbacks.Add(cb); return(Callbacks.Count == 1); }
protected void Create(Type cTypeShared) { Helper.InitializeTCPChannel(); _cEffect = (shared.Effect)Activator.CreateInstance(cTypeShared, null, new object[] {Preferences.cUrlAttribute}); if (null == _cEffect) throw new Exception("невозможно создать удаленный эффект"); //TODO LANG (new Logger()).WriteDebug3("effect:create: [type:" + cTypeShared.ToString() + "][hc:" + _cEffect.GetHashCode() + "][hcl:" + GetHashCode() + "]"); _cCallbacks = new Callbacks(this); _cEffect.EventRaised += _cCallbacks.Callback; if (this is Container && _cEffect is shared.Container) ((shared.Container) _cEffect).ContainerEventRaised += _cCallbacks.ContainerCallback; (new Logger()).WriteDebug3("effect:create:return [type:" + cTypeShared.ToString() + "][hc:" + _cEffect.GetHashCode() + "]"); }
static Interop() { IPathResolver pathResolver = null; IPlatformLoader loader = null; if (Host.GetExportedSymbol != null) { // We are loading exported functions from the currently running executable. pathResolver = new Host.Loader(); loader = new Host.Loader(); } else { pathResolver = new DynamicLinkLibraryPathResolver(); loader = PlatformLoaderBase.SelectPlatformLoader(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // This custom path resolver attempts to do a DllImport to get the path that .NET decides. // It may load a special dll from a NuGet package. pathResolver = new WindowsDllImportLibraryPathResolver(pathResolver); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { pathResolver = new MacDllImportLibraryPathResolver(pathResolver); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { pathResolver = new LinuxDllImportLibraryPathResolver(pathResolver); } } var result = pathResolver.Resolve("QmlNet"); if (!result.IsSuccess) { throw new Exception("Unable to find the native Qml.Net library." + " Try calling \"RuntimeManager.DiscoverOrDownloadSuitableQtRuntime();\" in Program.Main()");; } var library = loader.LoadLibrary(result.Path); Callbacks = LoadInteropType <CallbacksInterop>(library, loader); NetTypeInfo = LoadInteropType <NetTypeInfoInterop>(library, loader); NetJsValue = LoadInteropType <NetJsValueInterop>(library, loader); NetMethodInfo = LoadInteropType <NetMethodInfoInterop>(library, loader); NetPropertyInfo = LoadInteropType <NetPropertyInfoInterop>(library, loader); NetTypeManager = LoadInteropType <NetTypeManagerInterop>(library, loader); QCoreApplication = LoadInteropType <QCoreApplicationInterop>(library, loader); QQmlApplicationEngine = LoadInteropType <QQmlApplicationEngineInterop>(library, loader); NetVariant = LoadInteropType <NetVariantInterop>(library, loader); NetReference = LoadInteropType <NetReferenceInterop>(library, loader); NetVariantList = LoadInteropType <NetVariantListInterop>(library, loader); NetTestHelper = LoadInteropType <NetTestHelperInterop>(library, loader); NetSignalInfo = LoadInteropType <NetSignalInfoInterop>(library, loader); QResource = LoadInteropType <QResourceInterop>(library, loader); NetDelegate = LoadInteropType <NetDelegateInterop>(library, loader); QQuickStyle = LoadInteropType <QQuickStyleInterop>(library, loader); QtInterop = LoadInteropType <QtInterop>(library, loader); Utilities = LoadInteropType <UtilitiesInterop>(library, loader); QtWebEngine = LoadInteropType <QtWebEngineInterop>(library, loader); QTest = LoadInteropType <QTestInterop>(library, loader); NetQObject = LoadInteropType <NetQObjectInterop>(library, loader); NetQObjectSignalConnection = LoadInteropType <NetQObjectSignalConnectionInterop>(library, loader); // RuntimeManager.ConfigureRuntimeDirectory may set these environment variables. // However, they only really work when called with Qt.PutEnv. Qt.PutEnv("QT_PLUGIN_PATH", Environment.GetEnvironmentVariable("QT_PLUGIN_PATH")); Qt.PutEnv("QML2_IMPORT_PATH", Environment.GetEnvironmentVariable("QML2_IMPORT_PATH")); var cb = DefaultCallbacks.Callbacks(); Callbacks.RegisterCallbacks(ref cb); }
public static unsafe extern int SetGraphOrderCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackGraphOrderCallback graphCallback, IntPtr arg);
public static unsafe extern int SetSampleRateCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackSampleRateCallback srateCallback, IntPtr arg);
public MTAudioProcessingTap (MTAudioProcessingTapCallbacks callbacks, MTAudioProcessingTapCreationFlags flags) { if (callbacks == null) throw new ArgumentNullException ("callbacks"); const MTAudioProcessingTapCreationFlags all_flags = MTAudioProcessingTapCreationFlags.PreEffects | MTAudioProcessingTapCreationFlags.PostEffects; if ((flags & all_flags) == all_flags) throw new ArgumentException ("Only one effect type can be set"); this.callbacks = callbacks; var c = new Callbacks (); unsafe { if (callbacks.Initialize != null) c.init = InitializeProxy; if (callbacks.Finalize != null) c.finalize = FinalizeProxy; if (callbacks.Prepare != null) c.prepare = PrepareProxy; if (callbacks.Unprepare != null) c.unprepare = UnprepareProxy; c.process = ProcessProxy; } // a GCHandle is needed because we do not have an handle before calling MTAudioProcessingTapCreate // and that will call the InitializeProxy. So using this (short-lived) GCHandle allow us to find back the // original managed instance gch = GCHandle.Alloc (this); c.clientInfo = (IntPtr)gch; var res = MTAudioProcessingTapCreate (IntPtr.Zero, ref c, flags, out handle); // we won't need the GCHandle after the Create call gch.Free (); if (res != 0) throw new ArgumentException (res.ToString ()); lock (handles) handles [handle] = this; }
public static extern int mama_createDictionary (ref IntPtr dictionary, IntPtr queue, Callbacks callbacks, IntPtr source, double timeout, int retries, IntPtr closure);
/// <summary>Handles computations for the image request.</summary> protected virtual void RequestImage_Internal(string url, Func <Texture2D> loadFromDisk, Action <Texture2D> saveToDisk, Action <Texture2D> onSuccess, Action <WebRequestError> onError) { Debug.Assert(onSuccess != null); // early out if (string.IsNullOrEmpty(url)) { onSuccess(null); return; } // init vars Callbacks callbacks = null; // check cache Texture2D texture = null; if (this.cache.TryGetValue(url, out texture)) { onSuccess(texture); return; } // check currently downloading if (this.m_callbackMap.TryGetValue(url, out callbacks)) { // add callbacks callbacks.succeeded.Add(onSuccess); if (onError != null) { callbacks.failed.Add(onError); } return; } // check disk if (loadFromDisk != null) { texture = loadFromDisk(); if (texture != null) { this.cache.Add(url, texture); onSuccess(texture); return; } } // create new callbacks entry callbacks = new Callbacks() { succeeded = new List <Action <Texture2D> >(), failed = new List <Action <WebRequestError> >(), }; this.m_callbackMap.Add(url, callbacks); // add functions if (saveToDisk != null) { callbacks.succeeded.Add(saveToDisk); } callbacks.succeeded.Add(onSuccess); // start download this.DownloadImage(url); }
/// <summary>Handles computations for the image request.</summary> protected virtual void RequestImage_Internal <E>(IMultiSizeImageLocator <E> locator, E size, Func <Texture2D> loadFromDisk, Action <Texture2D> saveToDisk, Action <Texture2D> onSuccess, Action <Texture2D> onFallback, Action <WebRequestError> onError) { Debug.Assert(locator != null); Debug.Assert(onSuccess != null); // init vars string url = locator.GetSizeURL(size); Callbacks callbacks = null; // check for null URL if (string.IsNullOrEmpty(url)) { #if UNITY_EDITOR if (this.logDownloads) { Debug.Log("[mod.io] Attempted to fetch image with a Null or Empty" + " url in the locator."); } #endif onSuccess(null); return; } // check cache Texture2D texture = null; if (this.cache.TryGetValue(url, out texture)) { onSuccess(texture); return; } // check currently downloading if (this.m_callbackMap.TryGetValue(url, out callbacks)) { // add callbacks callbacks.succeeded.Add(onSuccess); if (onError != null) { callbacks.failed.Add(onError); } // check for fallback if (onFallback != null) { Texture2D fallback = FindFallbackTexture(locator); if (fallback != null) { onFallback(fallback); } } return; } // check disk if (loadFromDisk != null) { texture = loadFromDisk(); if (texture != null) { this.cache.Add(url, texture); onSuccess(texture); return; } } // create new callbacks entry callbacks = new Callbacks() { succeeded = new List <Action <Texture2D> >(), failed = new List <Action <WebRequestError> >(), }; this.m_callbackMap.Add(url, callbacks); // add functions if (saveToDisk != null) { callbacks.succeeded.Add(saveToDisk); } callbacks.succeeded.Add(onSuccess); // check for fallback if (onFallback != null) { Texture2D fallback = FindFallbackTexture(locator); if (fallback != null) { onFallback(fallback); } } // start download this.DownloadImage(url); }
private static extern void Fiftytwo_PlayerPrefsHooks_SetCallbacks(Callbacks callbacks);
internal void OnBeforeNavigate2(object pDisp, ref object URL, ref object flags, ref object targetFrameName, ref object postData, ref object headers, ref bool cancel) { var methodParameters = new [] { URL, flags, postData, headers }; Callbacks.raiseRegistedCallbacks(BeforeNavigate, methodParameters); }
/// <summary> /// Initializes a new instance of the <see cref="Scheduler"/> class. /// </summary> /// <param name="callbacks">The callbacks.</param> public Scheduler(Callbacks callbacks) => this.Initialize(callbacks);
private static void TestStruct() { Console.WriteLine("Testing Structs"); SequentialStruct ss = new SequentialStruct(); ss.f0 = 100; ss.f1 = 1; ss.f2 = 10.0f; ss.f3 = "Hello"; ThrowIfNotEquals(true, StructTest(ss), "Struct marshalling scenario1 failed."); StructTest_ByRef(ref ss); ThrowIfNotEquals(true, ss.f1 == 2 && ss.f2 == 11.0 && ss.f3.Equals("Ifmmp"), "Struct marshalling scenario2 failed."); SequentialStruct ss2 = new SequentialStruct(); StructTest_ByOut(out ss2); ThrowIfNotEquals(true, ss2.f0 == 1 && ss2.f1 == 1.0 && ss2.f2 == 1.0 && ss2.f3.Equals("0123456"), "Struct marshalling scenario3 failed."); NesterOfSequentialStruct.SequentialStruct ss3 = new NesterOfSequentialStruct.SequentialStruct(); ss3.f1 = 10.0f; ss3.f2 = 123; ThrowIfNotEquals(true, StructTest_Sequential2(ss3), "Struct marshalling scenario1 failed."); ExplicitStruct es = new ExplicitStruct(); es.f1 = 100; es.f2 = 100.0f; es.f3 = "Hello"; ThrowIfNotEquals(true, StructTest_Explicit(es), "Struct marshalling scenario4 failed."); NestedStruct ns = new NestedStruct(); ns.f1 = 100; ns.f2 = es; ThrowIfNotEquals(true, StructTest_Nested(ns), "Struct marshalling scenario5 failed."); SequentialStruct[] ssa = null; ThrowIfNotEquals(true, IsNULL(ssa), "Non-blittable array null check failed"); ssa = new SequentialStruct[3]; for (int i = 0; i < 3; i++) { ssa[i].f1 = 0; ssa[i].f1 = i; ssa[i].f2 = i * i; ssa[i].f3 = i.LowLevelToString(); } ThrowIfNotEquals(true, StructTest_Array(ssa, ssa.Length), "Array of struct marshalling failed"); InlineString ils = new InlineString(); InlineStringTest(ref ils); ThrowIfNotEquals("Hello World!", ils.name, "Inline string marshalling failed"); InlineArrayStruct ias = new InlineArrayStruct(); ias.inlineArray = new short[128]; for (short i = 0; i < 128; i++) { ias.inlineArray[i] = i; } ias.inlineString = "Hello"; InlineUnicodeStruct ius = new InlineUnicodeStruct(); ius.inlineString = "Hello World"; ThrowIfNotEquals(true, InlineArrayTest(ref ias, ref ius), "inline array marshalling failed"); bool pass = true; for (short i = 0; i < 128; i++) { if (ias.inlineArray[i] != i + 1) { pass = false; } } ThrowIfNotEquals(true, pass, "inline array marshalling failed"); ThrowIfNotEquals("Hello World", ias.inlineString, "Inline ByValTStr Ansi marshalling failed"); ThrowIfNotEquals("Hello World", ius.inlineString, "Inline ByValTStr Unicode marshalling failed"); pass = false; AutoStruct autoStruct = new AutoStruct(); try { // passing struct with Auto layout should throw exception. StructTest_Auto(autoStruct); } catch (Exception) { pass = true; } ThrowIfNotEquals(true, pass, "Struct marshalling scenario6 failed."); Callbacks callbacks = new Callbacks(); callbacks.callback0 = new Callback0(callbackFunc0); callbacks.callback1 = new Callback1(callbackFunc1); callbacks.callback2 = new Callback2(callbackFunc2); ThrowIfNotEquals(true, RegisterCallbacks(ref callbacks), "Scenario 7: Struct with delegate marshalling failed"); }
/** * start purchase. */ public IEnumerator PurchaseAsync( string purchaseId, string productId, Action <string> purchaseSucceeded, Action <string, PurchaseError, string, AutoyaStatus> purchaseFailed ) { if (Application.internetReachability == NetworkReachability.NotReachable) { purchaseFailed(purchaseId, PurchaseError.Offline, "network is offline.", new AutoyaStatus()); yield break; } if (routerState != RouterState.PurchaseReady) { switch (routerState) { case RouterState.GettingTransaction: case RouterState.Purchasing: { purchaseFailed(purchaseId, PurchaseError.AlreadyPurchasing, "purchasing another product now. wait then retry.", new AutoyaStatus()); break; } default: { purchaseFailed(purchaseId, PurchaseError.UnknownError, "state is:" + routerState, new AutoyaStatus()); break; } } yield break; } if (verifiedProducts != null) { var verified = false; foreach (var verifiedProduct in verifiedProducts) { if (verifiedProduct.productId == productId && verifiedProduct.isAvailableToThisPlayer) { verified = true; } } if (!verified) { purchaseFailed(purchaseId, PurchaseError.UnavailableProduct, "this product is not available.", new AutoyaStatus()); yield break; } } // renew callback. callbacks = new Callbacks(null, string.Empty, string.Empty, tId => {}, (tId, error, reason, autoyaStatud) => {}); var ticketUrl = PurchaseSettings.PURCHASE_URL_TICKET; var data = productId; routerState = RouterState.GettingTransaction; var connectionId = PurchaseSettings.PURCHASE_CONNECTIONID_TICKET_PREFIX + Guid.NewGuid().ToString(); var cor = HttpPost( connectionId, ticketUrl, data, (conId, resultData) => { var ticketId = onTicketResponse(resultData); TicketReceived(purchaseId, productId, ticketId, purchaseSucceeded, purchaseFailed); }, (conId, code, reason, autoyaStatus) => { purchaseFailed(purchaseId, PurchaseError.TicketGetError, "code:" + code + " reason:" + reason, autoyaStatus); routerState = RouterState.PurchaseReady; } ); while (cor.MoveNext()) { yield return(null); } }
public static unsafe extern int SetClientRegistrationCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackClientRegistrationCallback registrationCallback, IntPtr arg);
public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects2 creationEffects, ICreationResult templateCreationResult, string outputBasePath) { bool allSucceeded = true; IEnumerable <string> targetFiles = null; if (actionConfig.Args.TryGetValue("files", out string specificFilesString)) { JToken config = JToken.Parse(specificFilesString); if (config.Type == JTokenType.String) { targetFiles = specificFilesString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).SelectMany(x => GetTargetForSource(creationEffects, x)); } else if (config is JArray arr) { List <string> allFiles = new List <string>(); foreach (JToken child in arr) { if (child.Type != JTokenType.String) { continue; } allFiles.AddRange(GetTargetForSource(creationEffects, child.ToString())); } if (allFiles.Count > 0) { targetFiles = allFiles; } } } else { //If the author didn't opt in to the new behavior by using "files", do things the old way return(Process(environment, actionConfig, templateCreationResult, outputBasePath)); } if (targetFiles is null) { environment.Host.LogMessage(string.Format(LocalizableStrings.CouldntDetermineFilesToRestore)); return(false); } foreach (string targetRelativePath in targetFiles) { string pathToRestore = !string.IsNullOrEmpty(outputBasePath) ? Path.GetFullPath(Path.Combine(outputBasePath, targetRelativePath)) : targetRelativePath; if (string.IsNullOrEmpty(pathToRestore) || (!Directory.Exists(pathToRestore) && !Path.GetExtension(pathToRestore).EndsWith("proj", StringComparison.OrdinalIgnoreCase) && !Path.GetExtension(pathToRestore).Equals(".sln", StringComparison.OrdinalIgnoreCase) )) { continue; } environment.Host.LogMessage(string.Format(LocalizableStrings.RunningDotnetRestoreOn, pathToRestore)); // Prefer to restore the project in-proc vs. creating a new process. bool succeeded = false; if (Callbacks.RestoreProject != null) { succeeded = Callbacks.RestoreProject(pathToRestore); } else { Dotnet restoreCommand = Dotnet.Restore(pathToRestore).ForwardStdErr().ForwardStdOut(); Dotnet.Result commandResult = restoreCommand.Execute(); succeeded = commandResult.ExitCode == 0; } if (!succeeded) { environment.Host.LogMessage(LocalizableStrings.RestoreFailed); allSucceeded = false; } else { environment.Host.LogMessage(LocalizableStrings.RestoreSucceeded); } } return(allSucceeded); }
public static unsafe extern int SetPortRenameCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackPortRenameCallback renameCallback, IntPtr arg);
internal static extern bool RegisterCallbacks(ref Callbacks callbacks);
// called from ctor and OnDeserialized intialization paths void Initialize(Callbacks callbacks) { this.callbacks = callbacks; }
private void OnLoginResult(LoginResult result) { Callbacks.Add("OnResponse_InstLogin"); }
public static unsafe extern int SetBufferSizeCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackBufferSizeCallback bufsizeCallback, IntPtr arg);
private void OnLoginWithCustomId(LoginWithCustomIDRequest request) { Callbacks.Add("OnRequest_InstLogin"); }
public static unsafe extern int SetProcessCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackProcessCallback processCallback, IntPtr arg);
public static void DisconnectedCallback(int errorCode, string message) { Callbacks.disconnectedCallback(errorCode, message); }
public static unsafe extern int SetThreadInitCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackThreadInitCallback threadInitCallback, IntPtr arg);
public static void ErrorCallback(int errorCode, string message) { Callbacks.errorCallback(errorCode, message); }
private static extern void ossifer_web_view_set_callbacks(IntPtr ossifer, Callbacks callbacks);
public static void JoinCallback(string secret) { Callbacks.joinCallback(secret); }
private void handleDrop(DragEventArgs e) { Callbacks.raiseRegistedCallbacks(_onTableListDrop, new object[] { e }); }
public static void SpectateCallback(string secret) { Callbacks.spectateCallback(secret); }
internal void SetNativeCallback(Callbacks callbackType, CallbackDelegate callbackFunction) { _nativeCallbacks[callbackType] = callbackFunction; Functions.vp_callback_set(pointer, (int)callbackType, callbackFunction); }
public static void RequestCallback(ref DiscordUser request) { Callbacks.requestCallback(ref request); }
public static unsafe extern int SetPortConnectCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackPortConnectCallback connectCallback, IntPtr arg);
public static void ReadyCallback(ref DiscordUser connectedUser) { Callbacks.readyCallback(ref connectedUser); }
extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapCreate ( /* CFAllocatorRef*/ IntPtr allocator, /* const MTAudioProcessingTapCallbacks* */ ref Callbacks callbacks, MTAudioProcessingTapCreationFlags flags, /* MTAudioProcessingTapRef* */ out IntPtr tapOut);
/// <summary> /// Resets this instance. /// </summary> public void Reset() { Callbacks.Clear(); Functions.Clear(); }
public void OnDeserialized(Callbacks callbacks) { Initialize(callbacks); Fx.Assert(this.firstWorkItem != null || this.workItemQueue == null, "cannot have items in the queue unless we also have a firstWorkItem set"); }
public virtual void OnMessageReceived(Func <IModel, BasicDeliverEventArgs, Task> callback) { Callbacks.Add(callback); }
public Scheduler(Callbacks callbacks) { this.Initialize(callbacks); }
public static async Task <int> runIpcServerTcpClientRouter(CancellationToken token, string ipcServer, string tcpClient, int runtimeTimeoutMs, ILogger logger, Callbacks callbacks) { return(await runRouter(token, new IpcServerTcpClientRouterFactory(ipcServer, tcpClient, runtimeTimeoutMs, logger), callbacks).ConfigureAwait(false)); }
public Callbacks getMsgCallbacks() { Callbacks callbacks = new Callbacks(); callbacks.onComplete = new CompleteDelegate(this.OnComplete); callbacks.onTimeout = new TimeoutDelegate(this.OnTimeout); callbacks.onError = new ErrorDelegate(this.OnError); return callbacks; }
async static Task <int> runRouter(CancellationToken token, DiagnosticsServerRouterFactory routerFactory, Callbacks callbacks) { List <Task> runningTasks = new List <Task>(); List <Router> runningRouters = new List <Router>(); try { routerFactory.Start(); callbacks?.OnRouterStarted(routerFactory.TcpAddress); while (!token.IsCancellationRequested) { Task <Router> routerTask = null; Router router = null; try { routerTask = routerFactory.CreateRouterAsync(token); do { // Search list and clean up dead router instances before continue waiting on new instances. runningRouters.RemoveAll(IsRouterDead); runningTasks.Clear(); foreach (var runningRouter in runningRouters) { runningTasks.Add(runningRouter.RouterTaskCompleted.Task); } runningTasks.Add(routerTask); }while (await Task.WhenAny(runningTasks.ToArray()).ConfigureAwait(false) != routerTask); if (routerTask.IsFaulted || routerTask.IsCanceled) { //Throw original exception. routerTask.GetAwaiter().GetResult(); } if (routerTask.IsCompleted) { router = routerTask.Result; router.Start(); // Add to list of running router instances. runningRouters.Add(router); router = null; } routerTask.Dispose(); routerTask = null; } catch (Exception ex) { router?.Dispose(); router = null; routerTask?.Dispose(); routerTask = null; // Timing out on accepting new streams could mean that either the frontend holds an open connection // alive (but currently not using it), or we have a dead backend. If there are no running // routers we assume a dead backend. Reset current backend endpoint and see if we get // reconnect using same or different runtime instance. if (ex is BackendStreamTimeoutException && runningRouters.Count == 0) { routerFactory.Logger?.LogDebug("No backend stream available before timeout."); routerFactory.Reset(); } // Timing out on accepting a new runtime connection means there is no runtime alive. // Shutdown router to prevent instances to outlive runtime process (if auto shutdown is enabled). if (ex is RuntimeTimeoutException) { routerFactory.Logger?.LogInformation("No runtime connected before timeout."); routerFactory.Logger?.LogInformation("Starting automatic shutdown."); throw; } } } } catch (Exception ex) { routerFactory.Logger?.LogInformation($"Shutting down due to error: {ex.Message}"); } finally { if (token.IsCancellationRequested) { routerFactory.Logger?.LogInformation("Shutting down due to cancelation request."); } runningRouters.RemoveAll(IsRouterDead); runningRouters.Clear(); await routerFactory?.Stop(); callbacks?.OnRouterStopped(); routerFactory.Logger?.LogInformation("Router stopped."); } return(0); }
public static unsafe extern int SetFreewheelCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackFreewheelCallback freewheelCallback, IntPtr arg);
extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapCreate( /* CFAllocatorRef*/ IntPtr allocator, /* const MTAudioProcessingTapCallbacks* */ ref Callbacks callbacks, MTAudioProcessingTapCreationFlags flags, /* MTAudioProcessingTapRef* */ out IntPtr tapOut);
public static unsafe extern int SetLatencyCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackLatencyCallback latencyCallback, IntPtr arg);
public MTAudioProcessingTap(MTAudioProcessingTapCallbacks callbacks, MTAudioProcessingTapCreationFlags flags) { if (callbacks is null) { throw new ArgumentNullException(nameof(callbacks)); } const MTAudioProcessingTapCreationFlags all_flags = MTAudioProcessingTapCreationFlags.PreEffects | MTAudioProcessingTapCreationFlags.PostEffects; if ((flags & all_flags) == all_flags) { throw new ArgumentException("Only one effect type can be set"); } this.callbacks = callbacks; var c = new Callbacks(); unsafe { if (callbacks.Initialize is not null) { c.init = InitializeProxy; } if (callbacks.Finalize is not null) { c.finalize = FinalizeProxy; } if (callbacks.Prepare is not null) { c.prepare = PrepareProxy; } if (callbacks.Unprepare is not null) { c.unprepare = UnprepareProxy; } c.process = ProcessProxy; } // a GCHandle is needed because we do not have an handle before calling MTAudioProcessingTapCreate // and that will call the InitializeProxy. So using this (short-lived) GCHandle allow us to find back the // original managed instance var gch = GCHandle.Alloc(this); c.clientInfo = (IntPtr)gch; var res = MTAudioProcessingTapCreate(IntPtr.Zero, ref c, flags, out var handle); // we won't need the GCHandle after the Create call gch.Free(); if (res != 0) { throw new ArgumentException(res.ToString()); } InitializeHandle(handle); lock (handles) handles [handle] = this; }
public static unsafe extern int SetProcessThread(UnsafeStructs.jack_client_t* client, Callbacks.JackThreadCallback fun, IntPtr arg);
// ---------[ FUNCTIONALITY ]--------- /// <summary>Requests the image for a given locator.</summary> public virtual void RequestModLogo(int modId, LogoImageLocator locator, LogoSize size, Action <Texture2D> onLogoReceived, Action <Texture2D> onFallbackFound, Action <WebRequestError> onError) { Debug.Assert(locator != null); Debug.Assert(onLogoReceived != null); string url = locator.GetSizeURL(size); string fileName = locator.GetFileName(); // check cache and existing callbacks if (this.TryGetCacheOrSetCallbacks(url, onLogoReceived, onFallbackFound, onError)) { return; } // - Start new request - Callbacks callbacks = this.CreateCallbacksEntry(url, onLogoReceived, onError); // check for fallback callbacks.fallback = this.FindFallbackTexture(locator); if (onFallbackFound != null && callbacks.fallback != null) { onFallbackFound.Invoke(callbacks.fallback); } // add save function to download callback if (this.storeIfSubscribed) { callbacks.onTextureDownloaded = (texture) => { if (LocalUser.SubscribedModIds.Contains(modId)) { CacheClient.SaveModLogo(modId, fileName, size, texture, null); } }; } // start process by checking the cache CacheClient.LoadModLogo(modId, fileName, size, (texture) => { if (this == null) { return; } if (texture != null) { this.OnRequestSucceeded(url, texture); } else { // do the download this.DownloadImage(url); } }); }
public static unsafe extern void SetShutdownCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackShutdownCallback function, IntPtr arg);
/// <summary> /// Register a callback to handle modality worklists requests. /// </summary> /// <param name="context">OrthancPluginContext*</param> /// <param name="callback">OrthancPluginWorklistCallback</param> /// <returns></returns> public static OrthancPluginErrorCode OrthancPluginRegisterWorklistCallback(ref OrthancPluginContext context, Callbacks.OrthancPluginWorklistCallback callback) { IntPtr ptr = IntPtr.Zero; try { _OrthancPluginWorklistCallback pr = new _OrthancPluginWorklistCallback(); pr.callback = callback; int size = Marshal.SizeOf(pr); ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(pr, ptr, true); return context.InvokeService(ref context, _OrthancPluginService._OrthancPluginService_RegisterWorklistCallback, ptr); } catch (Exception ex) { OrthancPluginLogError(ref context, ex.ToString()); return OrthancPluginErrorCode.OrthancPluginErrorCode_InternalError; } finally { Marshal.FreeHGlobal(ptr); } }
public static unsafe extern int SetXrunCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackXRunCallback xrunCallback, IntPtr arg);
public virtual void OnMessageReceived(Func <Message <string, byte[]>, Task> callback) { Callbacks.Add(callback); }
void createBuffers(BufferInfo bufferInfos, int numChannels, int bufferSize, Callbacks callbacks) { InvokeCheck("createBuffers", bufferInfos, numChannels, bufferSize, callbacks); }
public Thread sendMessage(IO2Message messageToSend) { return(Callbacks.raiseRegistedCallbacks(onMessages, new object[] { messageToSend })); }
public async Task EmitAsync(string eventName, object obj, EventHandler callback) { _packetId++; Callbacks.Add(_packetId, callback); await EmitAsync(eventName, _packetId, obj); }
public void OnDeserialized(Callbacks callbacks) { this.Initialize(callbacks); }