コード例 #1
0
        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);
            }
        }
コード例 #2
0
        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;
            }
        }
コード例 #3
0
ファイル: OssiferWebView.cs プロジェクト: knocte/banshee
        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);
        }
コード例 #4
0
        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;
        }
コード例 #5
0
ファイル: Lookup.cs プロジェクト: yzun/ice
 public bool AddCallback(TaskCompletionSource <IObjectPrx?> cb)
 {
     Callbacks.Add(cb);
     return(Callbacks.Count == 1);
 }
コード例 #6
0
ファイル: Effects.cs プロジェクト: ratsil/bethe.ingenie
		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() + "]");
		}
コード例 #7
0
        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);
        }
コード例 #8
0
 public static unsafe extern int SetGraphOrderCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackGraphOrderCallback graphCallback, IntPtr arg);
コード例 #9
0
 public static unsafe extern int SetSampleRateCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackSampleRateCallback srateCallback, IntPtr arg);
コード例 #10
0
		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;
		}
コード例 #11
0
ファイル: MamaDictionary.cs プロジェクト: jacobraj/MAMA
			public static extern int mama_createDictionary (ref IntPtr dictionary,
				IntPtr queue,
				Callbacks  callbacks,
				IntPtr source,
				double timeout,
				int retries,
				IntPtr closure);
コード例 #12
0
        /// <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);
        }
コード例 #13
0
        /// <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);
        }
コード例 #14
0
 private static extern void Fiftytwo_PlayerPrefsHooks_SetCallbacks(Callbacks callbacks);
コード例 #15
0
        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);
        }
コード例 #16
0
 /// <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);
コード例 #17
0
ファイル: PInvoke.cs プロジェクト: zaccharles/corert
        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");
        }
コード例 #18
0
ファイル: PurchaseRouter.cs プロジェクト: ly774508966/Autoya
        /**
         *      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);
            }
        }
コード例 #19
0
ファイル: PortCallbackApi.cs プロジェクト: residuum/JackSharp
 public static unsafe extern int SetClientRegistrationCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackClientRegistrationCallback registrationCallback, IntPtr arg);
コード例 #20
0
        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);
        }
コード例 #21
0
ファイル: PortCallbackApi.cs プロジェクト: residuum/JackSharp
 public static unsafe extern int SetPortRenameCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackPortRenameCallback renameCallback, IntPtr arg);
コード例 #22
0
ファイル: PInvoke.cs プロジェクト: Maximys/runtime
 internal static extern bool RegisterCallbacks(ref Callbacks callbacks);
コード例 #23
0
 // called from ctor and OnDeserialized intialization paths
 void Initialize(Callbacks callbacks)
 {
     this.callbacks = callbacks;
 }
コード例 #24
0
 private void OnLoginResult(LoginResult result)
 {
     Callbacks.Add("OnResponse_InstLogin");
 }
コード例 #25
0
 public static unsafe extern int SetBufferSizeCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackBufferSizeCallback bufsizeCallback, IntPtr arg);
コード例 #26
0
 private void OnLoginWithCustomId(LoginWithCustomIDRequest request)
 {
     Callbacks.Add("OnRequest_InstLogin");
 }
コード例 #27
0
 public static unsafe extern int SetProcessCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackProcessCallback processCallback, IntPtr arg);
コード例 #28
0
ファイル: DiscordRpc.cs プロジェクト: AudioSensei/discord-rpc
 public static void DisconnectedCallback(int errorCode, string message)
 {
     Callbacks.disconnectedCallback(errorCode, message);
 }
コード例 #29
0
 public static unsafe extern int SetThreadInitCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackThreadInitCallback threadInitCallback, IntPtr arg);
コード例 #30
0
ファイル: DiscordRpc.cs プロジェクト: AudioSensei/discord-rpc
 public static void ErrorCallback(int errorCode, string message)
 {
     Callbacks.errorCallback(errorCode, message);
 }
コード例 #31
0
ファイル: OssiferWebView.cs プロジェクト: knocte/banshee
 private static extern void ossifer_web_view_set_callbacks(IntPtr ossifer, Callbacks callbacks);
コード例 #32
0
ファイル: DiscordRpc.cs プロジェクト: AudioSensei/discord-rpc
 public static void JoinCallback(string secret)
 {
     Callbacks.joinCallback(secret);
 }
コード例 #33
0
 private void handleDrop(DragEventArgs e)
 {
     Callbacks.raiseRegistedCallbacks(_onTableListDrop, new object[] { e });
 }
コード例 #34
0
ファイル: DiscordRpc.cs プロジェクト: AudioSensei/discord-rpc
 public static void SpectateCallback(string secret)
 {
     Callbacks.spectateCallback(secret);
 }
コード例 #35
0
ファイル: Instance.CoreEvents.cs プロジェクト: edwinr/VPNet
 internal void SetNativeCallback(Callbacks callbackType, CallbackDelegate callbackFunction)
 {
     _nativeCallbacks[callbackType] = callbackFunction;
     Functions.vp_callback_set(pointer, (int)callbackType, callbackFunction);
 }
コード例 #36
0
ファイル: DiscordRpc.cs プロジェクト: AudioSensei/discord-rpc
 public static void RequestCallback(ref DiscordUser request)
 {
     Callbacks.requestCallback(ref request);
 }
コード例 #37
0
ファイル: PortCallbackApi.cs プロジェクト: residuum/JackSharp
 public static unsafe extern int SetPortConnectCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackPortConnectCallback connectCallback, IntPtr arg);
コード例 #38
0
ファイル: DiscordRpc.cs プロジェクト: AudioSensei/discord-rpc
 public static void ReadyCallback(ref DiscordUser connectedUser)
 {
     Callbacks.readyCallback(ref connectedUser);
 }
コード例 #39
0
		extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapCreate (
			/* CFAllocatorRef*/ IntPtr allocator, 
			/* const MTAudioProcessingTapCallbacks* */ ref Callbacks callbacks, 
			MTAudioProcessingTapCreationFlags flags,
			/* MTAudioProcessingTapRef* */ out IntPtr tapOut);
コード例 #40
0
 /// <summary>
 /// Resets this instance.
 /// </summary>
 public void Reset()
 {
     Callbacks.Clear();
     Functions.Clear();
 }
コード例 #41
0
 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");
 }
コード例 #42
0
ファイル: RabbitMqConsumer.cs プロジェクト: linxy5326/LinFx
 public virtual void OnMessageReceived(Func <IModel, BasicDeliverEventArgs, Task> callback)
 {
     Callbacks.Add(callback);
 }
コード例 #43
0
 public Scheduler(Callbacks callbacks)
 {
     this.Initialize(callbacks);
 }
コード例 #44
0
 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));
 }
コード例 #45
0
ファイル: MamaDictionary.cs プロジェクト: jacobraj/MAMA
			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;
			}
コード例 #46
0
        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);
        }
コード例 #47
0
 public static unsafe extern int SetFreewheelCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackFreewheelCallback freewheelCallback, IntPtr arg);
コード例 #48
0
 extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapCreate(
     /* CFAllocatorRef*/ IntPtr allocator,
     /* const MTAudioProcessingTapCallbacks* */ ref Callbacks callbacks,
     MTAudioProcessingTapCreationFlags flags,
     /* MTAudioProcessingTapRef* */ out IntPtr tapOut);
コード例 #49
0
 public static unsafe extern int SetLatencyCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackLatencyCallback latencyCallback, IntPtr arg);
コード例 #50
0
        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;
        }
コード例 #51
0
 public static unsafe extern int SetProcessThread(UnsafeStructs.jack_client_t* client, Callbacks.JackThreadCallback fun, IntPtr arg);
コード例 #52
0
        // ---------[ 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);
                }
            });
        }
コード例 #53
0
 public static unsafe extern void SetShutdownCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackShutdownCallback function, IntPtr arg);
コード例 #54
0
        /// <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);
            }
        }
コード例 #55
0
 public static unsafe extern int SetXrunCallback(UnsafeStructs.jack_client_t* client, Callbacks.JackXRunCallback xrunCallback, IntPtr arg);
コード例 #56
0
 public virtual void OnMessageReceived(Func <Message <string, byte[]>, Task> callback)
 {
     Callbacks.Add(callback);
 }
コード例 #57
0
ファイル: AsioWrapper.cs プロジェクト: alexbv16/LiveSPICE
 void createBuffers(BufferInfo bufferInfos, int numChannels, int bufferSize, Callbacks callbacks)
 {
     InvokeCheck("createBuffers", bufferInfos, numChannels, bufferSize, callbacks);
 }
コード例 #58
0
 public Thread sendMessage(IO2Message messageToSend)
 {
     return(Callbacks.raiseRegistedCallbacks(onMessages, new object[] { messageToSend }));
 }
コード例 #59
0
 public async Task EmitAsync(string eventName, object obj, EventHandler callback)
 {
     _packetId++;
     Callbacks.Add(_packetId, callback);
     await EmitAsync(eventName, _packetId, obj);
 }
コード例 #60
0
 public void OnDeserialized(Callbacks callbacks)
 {
     this.Initialize(callbacks);
 }