/// <summary>
        /// Initialize selected object.
        /// </summary>
        /// <param name="_prefab"> Prefab asset reference. </param>
        /// <param name="_callBack"></param>
        /// <returns> False if there is no this prefab type in PoolHandler setup.
        /// True if you setted this type up. </returns>
        private bool InitializeObject(AssetReference _prefab, Action <PoolObject> _callBack)
        {
            PoolObject _poolObject = null;
            int        _poolIndex  = -1;

            if (TryFindPoolObjectDataByAssetReference(_prefab, ref _poolIndex) == false)
            {
                Debug.LogWarning("There is no this prefab type in setup");
                return(false);
            }

            ObjectsRegister _register = objectPools[_poolIndex].Register;

            if (_register.TryGetAvailableObject(ref _poolObject) == true)
            {
                objectPools[_poolIndex].UpdateRegister(_register);
                _poolObject.OnHandlerReturnInvoke += ReturnToPool;
                _callBack?.Invoke(_poolObject);
                _poolObject.GetFromPool(_poolIndex);
                return(true);
            }

            ObjectInstatniationCallback _instatniationCallback = InitializeNewPoolObject;

            InvokeData _invokeData = new InvokeData(_poolObject, _poolIndex, _callBack);

            StartCoroutine(InstantiateObject(_prefab, _instatniationCallback, _invokeData));

            return(true);
        }
        public override void OnUpdate()
        {
            base.OnUpdate();
            currentInvokeTime += Time.deltaTime * TimeScale;

            for (int i = 0; i < invokeList.Count; i++)
            {
                InvokeData data = invokeList [i];
                if (currentInvokeTime - data.time >= data.delay)
                {
                    if (data.isRepeat)
                    {
                        data.delay += data.repeatTime;
                    }
                    else
                    {
                        data.remove = true;
                    }
                    if (data.callback != null)
                    {
                        data.callback();
                    }
                }
            }
            invokeList.RemoveAll((o) => {
                return(o.remove);
            });
        }
Exemple #3
0
        public void Run_ReportsInvocationSuccess()
        {
            // arrange
            A.CallTo(() => _runtime.KeepInvokeLoopRunning()).ReturnsNextFromSequence(true, false);

            var invokeData = new InvokeData {
                RequestId = Guid.NewGuid().ToString()
            };

            A.CallTo(() => _runtime.GetNextInvocation()).Returns(invokeData);

            var environment = A.Fake <IEnvironment>();

            A.CallTo(() => _runtime.Environment).Returns(environment);

            var outputStream = new MemoryStream();

            A.CallTo(() => _runner.Handle(A <Stream> .Ignored, A <ILambdaContext> .Ignored))
            .Returns(outputStream);

            // act
            _bootstrap.Run();

            // assert
            A.CallTo(() => _runtime.ReportInvocationSuccess(invokeData.RequestId, outputStream))
            .MustHaveHappened();
        }
Exemple #4
0
        public void Run_SetsXrayEnvironmentVariableBeforeCallingHandle()
        {
            // arrange
            A.CallTo(() => _runtime.KeepInvokeLoopRunning()).ReturnsNextFromSequence(true, false);

            var invokeData = new InvokeData
            {
                XAmznTraceId  = Guid.NewGuid().ToString(),
                InputStream   = new MemoryStream(),
                LambdaContext = A.Fake <ILambdaContext>()
            };

            A.CallTo(() => _runtime.GetNextInvocation()).Returns(invokeData);

            var environment = A.Fake <IEnvironment>();

            A.CallTo(() => _runtime.Environment).Returns(environment);

            // act
            _bootstrap.Run();

            // assert
            A.CallTo(() => environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", invokeData.XAmznTraceId))
            .MustHaveHappened()
            .Then(A.CallTo(() => _runner.Handle(invokeData.InputStream, invokeData.LambdaContext)).MustHaveHappened());
        }
 /// <summary>
 /// Initialize new instantiated pool object.
 /// </summary>
 private void InitializeNewPoolObject(InvokeData _invokeData)
 {
     objectPools[_invokeData.PoolIndex].RegisterObject(_invokeData.PoolObject);
     _invokeData.Callback?.Invoke(_invokeData.PoolObject);
     _invokeData.PoolObject.GetFromPool(_invokeData.PoolIndex);
     _invokeData.PoolObject.OnHandlerReturnInvoke += ReturnToPool;
 }
            public ValueTask <IService> CreateService(IFactoryContext factoryContext,
                                                      Uri?baseUri,
                                                      InvokeData invokeData,
                                                      IServiceCommunication serviceCommunication,
                                                      CancellationToken token)
            {
                switch (_creators[invokeData.Type])
                {
                case IServiceCatalog.Creator creator:
                    var service = creator();

                    service.Start(baseUri, invokeData, serviceCommunication);

                    return(new ValueTask <IService>(service));

                case IServiceCatalog.ServiceCreator creator:
                    return(new ValueTask <IService>(creator(baseUri, invokeData, serviceCommunication)));

                case IServiceCatalog.ServiceCreatorAsync creator:
                    return(creator(factoryContext, baseUri, invokeData, serviceCommunication, token));

                default:
                    return(Infra.Unexpected <ValueTask <IService> >(_creators[invokeData.Type]?.GetType()));
                }
            }
        public void Invoke(float delay, System.Action callback)
        {
            InvokeData invoke = new InvokeData();

            invoke.delay    = delay;
            invoke.isRepeat = false;
            invoke.callback = callback;
            invoke.time     = currentInvokeTime;
            invokeList.Add(invoke);
        }
        public void InvokeRepeating(float delay, float repeatTime, System.Action callback)
        {
            InvokeData invoke = new InvokeData();

            invoke.delay      = delay;
            invoke.isRepeat   = true;
            invoke.repeatTime = repeatTime;
            invoke.callback   = callback;
            invoke.time       = currentInvokeTime;
            invokeList.Add(invoke);
        }
        public void BeginInvoke(Delegate method, params object[] args)
        {
            InvokeData k = new InvokeData {
                method = method, args = args
            };

            lock (methodsToInvoke)
            {
                methodsToInvoke.Add(k);
            }
        }
Exemple #10
0
    static public void DrawInvokeData(InvokeData invoke)
    {
        EditorGUILayout.BeginHorizontal();
        if (EditorTools.DrawButton("R", "Reset script", (invoke.script != null), 20f))
        {
            invoke.script = invoke.newScript = null;
        }
        if (invoke.script != null)
        {
            string title   = invoke.script.GetType().ToString();
            string tooltip = "Set component " + title;
            GUILayout.Label(new GUIContent(title, tooltip), GUILayout.MinWidth(20f), GUILayout.MaxWidth(90f));
        }
        MonoBehaviour newScript = (MonoBehaviour)EditorGUILayout.ObjectField(invoke.script, typeof(MonoBehaviour), true);

        if (newScript != invoke.script)
        {
            invoke.newScript = newScript;
        }
        invoke.method = EditorGUILayout.TextField(invoke.method);
        EditorGUILayout.EndHorizontal();
        if (invoke.newScript != null)
        {
            MonoBehaviour[] components = invoke.newScript.GetComponents <MonoBehaviour>();
            if (components.Length > 1)
            {
                for (int j = 0; j < components.Length; j++)
                {
                    if (EditorTools.DrawButton("Set " + components[j].GetType().ToString() + " script"))
                    {
                        invoke.script    = components[j];
                        invoke.newScript = null;
                    }
                }
                if (EditorTools.DrawButton("Undo"))
                {
                    invoke.newScript = null;
                }
                EditorGUILayout.Space();
            }
            else
            {
                invoke.script    = components[0];
                invoke.newScript = null;
            }
        }
    }
Exemple #11
0
        /// <summary>
        /// Executes the provided action synchronously. This means that this function returns only after the provided action was executed.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        public void Invoke(Action action)
        {
            var evnt       = new System.Threading.AutoResetEvent(false);
            var invokeData = new InvokeData {
                @Action = action, @Event = evnt
            };

            _invokerQueue.Enqueue(invokeData);
            _triggeringEvent.Set();

            evnt.WaitOne();

            if (invokeData.Exception != null)
            {
                throw invokeData.Exception;
            }
        }
        async ValueTask IExternalCommunication.StartInvoke(InvokeData invokeData, CancellationToken token)
        {
            try
            {
                if (_options.ExternalCommunication is not {
                } externalCommunication)
                {
                    throw NoExternalCommunication();
                }

                await externalCommunication.StartInvoke(invokeData, token).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw new CommunicationException(ex, _sessionId);
            }
        }
		void BeginInvoke (InvokeHandler action, TimeSpan interval)
		{
			DateTime dt = DateTime.UtcNow.Add (interval);
			lock (callbacks) {
				bool inserted = false;
				var data = new InvokeData () { Action = action, Time = dt };
				for (int i = 0; i < callbacks.Count; i++) {
					if (dt > callbacks [i].Time) {
						callbacks.Insert (i, data);
						inserted = true;
						break;
					}
				}
				if (!inserted)
					callbacks.Add (data);
				callback_event.Set ();
			}
		}
        private void OnBeginInvokeClients(object asyncResult)
        {
            AsyncResultNoResult ar = asyncResult as AsyncResultNoResult;

            try {
                // Perform the operation; if sucessful set the result
                InvokeData invokeData = ar.AsyncState as InvokeData;
                //Restore context
                FluorineWebSafeCallContext.SetData(FluorineContext.FluorineContextKey, invokeData.Context);
                InvokeClients(invokeData.Method, invokeData.Arguments, invokeData.Callback, invokeData.IgnoreSelf, invokeData.TargetScope);
                ar.SetAsCompleted(null, false);
            } catch (Exception ex) {
                // If operation fails, set the exception
                ar.SetAsCompleted(ex, false);
            } finally {
                FluorineWebSafeCallContext.FreeNamedDataSlot(FluorineContext.FluorineContextKey);
            }
        }
        /// <summary>
        /// Initialize all pre-instantiated objects.
        /// </summary>
        private void InitializePools()
        {
            for (int i = 0; i < objectPools.Length; i++)
            {
                if (objectPools[i].InstantiateObjectOnAwake == false)
                {
                    continue;
                }

                for (int j = 0; j < objectPools[i].MaxInstancesAmount; j++)
                {
                    ObjectInstatniationCallback _callback = InitializeNewPoolObjectOnAwake;

                    InvokeData _invokeData = new InvokeData(null, i, null);

                    StartCoroutine(InstantiateObject(objectPools[i].Prefab, _callback, _invokeData));
                }
            }
        }
Exemple #16
0
        public virtual async ValueTask <InvokeId> Start(IIdentifier stateId, IExecutionContext executionContext, CancellationToken token)
        {
            if (stateId is null)
            {
                throw new ArgumentNullException(nameof(stateId));
            }
            if (executionContext is null)
            {
                throw new ArgumentNullException(nameof(executionContext));
            }

            var invokeId = InvokeId.New(stateId, _invoke.Id);

            if (IdLocationEvaluator is not null)
            {
                await IdLocationEvaluator.SetValue(invokeId, executionContext, token).ConfigureAwait(false);
            }

            var type = TypeExpressionEvaluator is not null?ToUri(await TypeExpressionEvaluator.EvaluateString(executionContext, token).ConfigureAwait(false)) : _invoke.Type;

            var source = SourceExpressionEvaluator is not null?ToUri(await SourceExpressionEvaluator.EvaluateString(executionContext, token).ConfigureAwait(false)) : _invoke.Source;

            var rawContent = ContentBodyEvaluator is IStringEvaluator rawContentEvaluator ? await rawContentEvaluator.EvaluateString(executionContext, token).ConfigureAwait(false) : null;

            var content = await DataConverter.GetContent(ContentBodyEvaluator, ContentExpressionEvaluator, executionContext, token).ConfigureAwait(false);

            var parameters = await DataConverter.GetParameters(NameEvaluatorList, ParameterList, executionContext, token).ConfigureAwait(false);

            Infra.NotNull(type);

            var invokeData = new InvokeData(invokeId, type)
            {
                Source     = source,
                RawContent = rawContent,
                Content    = content,
                Parameters = parameters
            };

            await executionContext.StartInvoke(invokeData, token).ConfigureAwait(false);

            return(invokeId);
        }
        /// <summary>
        /// Instantiate prefab and make it as a child.
        /// </summary>
        /// <param name="_prefab"> Prefab to instantiate. </param>
        /// <param name="_callback"> Instantiation callback. </param>
        /// <param name="_invokeData"> Invoke callback. </param>
        private IEnumerator InstantiateObject(
            AssetReference _prefab,
            ObjectInstatniationCallback _callback,
            InvokeData _invokeData)
        {
            AsyncOperationHandle <GameObject> _handle = _prefab.InstantiateAsync(transform);

            while (_handle.Status == AsyncOperationStatus.None)
            {
                yield return(null);
            }

            GameObject _object = _handle.Result;

            PoolObject _poolObject = _object.GetComponent <PoolObject>();

            _invokeData.PoolObject = _poolObject;

            _callback?.Invoke(_invokeData);
        }
        protected virtual void Update()
        {
            if (scriptDataList == null)
            {
                return;
            }
            currentInvokeTime += Time.deltaTime;
            scriptDataList.RemoveAll(o => o.script.enabled == false);

            for (int i = 0; i < scriptDataList.Count; i++)
            {
                for (int j = 0; j < scriptDataList [i].invokeList.Count; j++)
                {
                    InvokeData data = scriptDataList [i].invokeList [j];
                    if (currentInvokeTime - data.time >= data.delay)
                    {
                        if (data.isRepeat)
                        {
                            data.delay += data.repeatTime;
                        }
                        else
                        {
                            data.remove = true;
                        }
                        if (data.callback != null)
                        {
                            data.callback();
                        }
                    }
                }
                scriptDataList [i].invokeList.RemoveAll((o) => {
                    return(o.remove);
                });
            }
            scriptDataList.RemoveAll(o => o.invokeList == null || o.invokeList.Count == 0);

            if (scriptDataList.Count == 0)
            {
                this.enabled = false;
            }
        }
        internal bool ScheduleInvocation(Component component, string methodName, float delay, float interval = InvokeOnceInterval)
        {
            if (component == null)
            {
                throw new ArgumentNullException(nameof(component));
            }

            if (methodName == null)
            {
                throw new ArgumentNullException(nameof(methodName));
            }

            //Needed because otherwise we could end up in an infinite loop invoking the same method over and over
            if (delay < 0)
            {
                throw new ArgumentOutOfRangeException("Invocation delay must be a positive value");
            }

            if (interval != InvokeOnceInterval && interval <= 0.0001f)
            {
                throw new ArgumentOutOfRangeException("Invocation interval must be greater than 0.0001");
            }

            if (!TryGetMethod(component, methodName, null, out var method))
            {
                return(false);
            }

            var data = new InvokeData
            {
                Component      = component,
                Method         = method,
                InvocationTime = (float)(_scene.Time.ElapsedTime + delay),
                Interval       = interval,
            };

            _invokeTargets.AddLast(data);

            return(true);
        }
        private void AddHelperInvoke(MonoBehaviour script, string methodKey, float delay, float repeatTime, System.Action callback)
        {
            if (this.enabled == false)
            {
                enabled = true;
            }

            ScriptData data = scriptDataList.Find(o => o.script.Equals(script));

            if (data == null)
            {
                data              = new ScriptData();
                data.invokeList   = new List <InvokeData> ();
                data.script       = script;
                currentInvokeTime = 0;
                scriptDataList.Add(data);
            }


            InvokeData invoke = new InvokeData();

            invoke.key   = methodKey;
            invoke.delay = delay;
            if (repeatTime <= 0)
            {
                invoke.isRepeat = false;
            }
            else
            {
                invoke.isRepeat = true;
            }
            invoke.repeatTime = repeatTime;
            invoke.callback   = callback;
            invoke.time       = currentInvokeTime;

            data.invokeList.Add(invoke);
        }
        void Run(object unused)
        {
            mDevice        = new XAudio2();
            masteringVoice = new MasteringVoice(mDevice);

            for (; ;)
            {
                int count = methodsToInvoke.Count;

                for (int i = 0; i < count; i++)
                {
                    if (stopThread)
                    {
                        break;
                    }

                    InvokeData k = methodsToInvoke[i];

                    k.method.DynamicInvoke(k.args);
                }

                lock (methodsToInvoke)
                {
                    methodsToInvoke.RemoveRange(0, count);
                }

                if (stopThread)
                {
                    break;
                }

                Thread.Sleep(1);
            }

            Dispose();
        }
Exemple #22
0
        /// <summary>
        /// Executes an action <paramref name="action"/> in a separate task (blocking). If the action (or a child task) wants to invoke the Gui thread, this is possible without deadlock.
        /// This procedure must be called only from the Gui thread. The procedure returns when the action has been finished.
        /// </summary>
        /// <param name="action">The action. Please not that the action is executed in a thread other than the Gui thread.</param>
        /// <exception cref="System.InvalidOperationException">Is thrown if this procedure is called from a thread that is not the Gui thread.</exception>
        public void FromGuiThreadExecute(Action action)
        {
            // we assume that this is the Gui thread
            if (_isInvokeRequiredForGuiThread())
            {
                throw new InvalidOperationException("This procedure must be called from the Gui thread only.");
            }

            var data = new InvokeData()
            {
                Task = new Task(action)
            };

            _invokerQueue.Push(data);
            data.Task.Start();

            Action guiAction;

            System.Threading.AutoResetEvent myEvent;
            for (; ;)
            {
                lock (data)
                {
                    guiAction      = data.GuiAction;
                    myEvent        = data.Event;
                    data.GuiAction = null;
                    data.Event     = null;
                }
                if (null != guiAction)
                {
                    guiAction();
                    myEvent.Set();
                }
                if (data.Task.Wait(1))
                {
                    break;
                }
            }

            guiAction = null;
            lock (_syncObject)
            {
                if (_invokerQueue.TryPop(out data))
                {
                    lock (data)
                    {
                        guiAction      = data.GuiAction;
                        myEvent        = data.Event;
                        data.GuiAction = null;
                        data.Event     = null;
                    }
                }
            }
            if (null != guiAction)
            {
                guiAction();
                myEvent.Set();
            }

            if (null != data.Task.Exception)
            {
                throw data.Task.Exception;
            }
        }
 /// <summary>
 /// 实例化InvokeResponse
 /// </summary>
 /// <param name="data"></param>
 public InvokeResponse(InvokeData data)
 {
     base.Count         = data.Count;
     base.Value         = data.Value;
     base.OutParameters = data.OutParameters;
 }
 /// <summary>
 /// Initialize new instantiated pool object on Awake.
 /// </summary>
 private void InitializeNewPoolObjectOnAwake(InvokeData _invokeData)
 {
     objectPools[_invokeData.PoolIndex].RegisterObject(_invokeData.PoolObject);
     _invokeData.PoolObject.gameObject.SetActive(false);
 }
Exemple #25
0
 private static bool IsDeleted(InvokeData data)
 {
     return data.cmp == null;
 }
Exemple #26
0
 public void DoInvoke(Component cmp, string funcName, float delay)
 {
     InvokeData item = new InvokeData(cmp, funcName, delay);
     this.invokeList.Add(item);
 }
Exemple #27
0
 private static bool IsDeleted(InvokeData data)
 {
     return(data.cmp == null);
 }
Exemple #28
0
    public void DoInvoke(Component cmp, string funcName, float delay)
    {
        InvokeData item = new InvokeData(cmp, funcName, delay);

        this.invokeList.Add(item);
    }
Exemple #29
0
		/// <summary>
		/// Executes the provided action synchronously. This means that this function returns only after the provided action was executed.
		/// </summary>
		/// <param name="action">The action to execute.</param>
		public void Invoke(Action action)
		{
			var evnt = new System.Threading.AutoResetEvent(false);
			var invokeData = new InvokeData { @Action = action, @Event = evnt };
			_invokerQueue.Enqueue(invokeData);
			_triggeringEvent.Set();

			evnt.WaitOne();

			if (invokeData.Exception != null)
				throw invokeData.Exception;
		}