Ejemplo n.º 1
0
        public TaskTimer(Action <object> callback, object state,
                         int millisecondsPeriod, bool waitForCallbackBeforeNextPeriod = true)
        {
            Task.Delay(millisecondsPeriod, Token).ContinueWith
                (async(task, s) =>
            {
                Tuple <Action <object>, object> tuple = (Tuple <Action <object>, object>)s;

                // Mientras no se cancele la tarea
                while (!IsCancellationRequested)
                {
                    // Ejecuta el callback
                    if (waitForCallbackBeforeNextPeriod)
                    {
                        tuple.Item1(tuple.Item2);
                    }
                    else
                    {
                        await Task.Run(() => tuple.Item1(tuple.Item2));
                    }
                    // Crea una nueva tarea para que se ejecute dentro de un tiempo
                    await Task.Delay(millisecondsPeriod, Token).ConfigureAwait(false);
                }
            },
                Tuple.Create(callback, state), CancellationToken.None,
                TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
        }
Ejemplo n.º 2
0
        private void Run <TInd, T>(Func <string, IWritableFeed <TInd, T> > newFile)
            where TInd : IComparable <TInd>
        {
            bool allowsDefaults           = typeof(T).IsValueType && typeof(TInd).IsValueType;
            Tuple <Func <long, T>, T> inf = TestUtils.GetObjInfo <T>();

            var minVal = allowsDefaults ? default(T) : inf.Item1(0);
            var val1   = inf.Item1(10);
            var val2   = inf.Item1(20);
            var maxVal = inf.Item2;

            using (var f = Open(newFile))
                Regular(f);

            using (var f = Open(newFile))
                TwoValueTest(f, minVal, maxVal);

            using (var f = Open(newFile))
                TwoValueTest(f, minVal, val1);

            using (var f = Open(newFile))
                TwoValueTest(f, val1, val2);

            using (var f = Open(newFile))
                TwoValueTest(f, val2, maxVal);
        }
Ejemplo n.º 3
0
        internal static void Point(Numeral x, Numeral y)
        {
            Tuple <Numeral, Numeral> point1 = ChurchTuple <Numeral, Numeral> .Create(x)(y);

            Numeral x1 = point1.Item1();
            Numeral y1 = point1.Item1();

            // Move up.
            Numeral y2 = y1.Increase();
            Tuple <Numeral, Numeral> point2 = ChurchTuple <Numeral, Numeral> .Create(x1)(y2);
        }
 public void BeginMessageLoop()
 {
     while (!m_Done)
     {
         Tuple <SendOrPostCallback, object> task = null;
         lock (m_Items)
         {
             if (m_Items.Count > 0)
             {
                 task = m_Items.Dequeue();
             }
         }
         if (task != null)
         {
             task.Item1(task.Item2);
             if (InnerException != null)
             {
                 throw new AggregateException("AsyncHelper执行的异步方法引发了一个异常", InnerException);
             }
         }
         else
         {
             m_WorkItemsWaiting.WaitOne();
         }
     }
 }
Ejemplo n.º 5
0
 public void BeginMessageLoop()
 {
     while (!done)
     {
         Tuple <SendOrPostCallback, object> task = null;
         lock (items)
         {
             if (items.Count > 0)
             {
                 task = items.Dequeue();
             }
         }
         if (task != null)
         {
             task.Item1(task.Item2);
             if (this.InnerException != null) // the method threw an exeption
             {
                 if (this.InnerException is TaskCanceledException)
                 {
                     throw new TimeoutException("AsyncHelpers.Run method threw a TaskCanceledException exception. This maybe be due to a timeout. See inner exception for details.", this.InnerException);
                 }
                 else
                 {
                     throw new AggregateException("AsyncHelpers.Run method threw an exception.", this.InnerException);
                 }
             }
         }
         else
         {
             workItemsWaiting.WaitOne();
         }
     }
 }
Ejemplo n.º 6
0
 public void Execute()
 {
     if (p.Item1())
     {
         p.Item2();
     }
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Adds the JavaScript statements that show the components.
 /// </summary>
 public void AddJsShowStatements(string statements)
 {
     if (jsShowAndHideStatementAdders != null)
     {
         jsShowAndHideStatementAdders.Item1(statements);
     }
 }
Ejemplo n.º 8
0
        public void BeginMessageLoop()
        {
            while (!_done)
            {
                Tuple <SendOrPostCallback, object> task = null;
                lock (_items)
                {
                    if (_items.Count > 0)
                    {
                        task = _items.Dequeue();
                    }
                }

                if (task != null)
                {
                    task.Item1(task.Item2);
                    if (InnerException is not null)
                    {
                        throw new AggregateException(
                                  $"{nameof(Async)}.{nameof(Async.RunSync)}: provided async function threw an exception.",
                                  InnerException
                                  );
                    }
                }
                else
                {
                    _workItemsWaiting.WaitOne();
                }
            }
        }
Ejemplo n.º 9
0
 public void BeginMessageLoop()
 {
     while (!done)
     {
         Tuple <SendOrPostCallback, object> task = null;
         if (System.Threading.Monitor.TryEnter(items, Config.local.thread_lock_timeout_seconds * 1000))
         {
             try
             {
                 if (items.Count > 0)
                 {
                     task = items.Dequeue();
                 }
             }
             finally
             {
                 System.Threading.Monitor.Exit(items);
             }
         }
         if (task != null)
         {
             task.Item1(task.Item2);
             if (InnerException != null) // the method threw an exeption
             {
                 throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
             }
         }
         else
         {
             workItemsWaiting.WaitOne();
         }
     }
 }
 private IEnumerator Start()
 {
     for (;;)
     {
         Tuple <SendOrPostCallback, object> entry = null;
         object obj = this.CallbackQueue;
         lock (obj)
         {
             if (this.CallbackQueue.Count > 0)
             {
                 entry = this.CallbackQueue.Dequeue();
             }
         }
         if (entry != null && entry.Item1 != null)
         {
             try
             {
                 entry.Item1(entry.Item2);
             }
             catch (Exception ex)
             {
                 Debug.Log(ex.ToString());
             }
         }
         yield return(null);
     }
     yield break;
 }
Ejemplo n.º 11
0
            //private IEnumerator Start() {
            //    UnitySynchronizationContext.SynchronizationContextBehavoir.< Start > c__Iterator0 < Start > c__Iterator = new UnitySynchronizationContext.SynchronizationContextBehavoir.< Start > c__Iterator0();

            //    < Start > c__Iterator.$this = this;
            //    return < Start > c__Iterator;
            //}
            //xia9000
            IEnumerator Start()
            {
                //uint num = (uint)this.$PC;
                //this.$PC = -1;
                //switch (num) {
                //    case 0u:
                //        break;
                //    case 1u:
                //        break;
                //    default:
                //        return false;
                //}
                Tuple <SendOrPostCallback, object> entry = null;
                var locvar0 = CallbackQueue;

                lock (locvar0){
                    if (CallbackQueue.Count > 0)
                    {
                        entry = CallbackQueue.Dequeue();
                    }
                }
                if (entry != null && entry.Item1 != null)
                {
                    try {
                        entry.Item1(entry.Item2);
                    } catch (Exception ex) {
                        UnityEngine.Debug.Log(ex.ToString());
                    }
                }
                yield return(null);
            }
Ejemplo n.º 12
0
 public void BeginMessageLoop()
 {
     while (!done)
     {
         Tuple <SendOrPostCallback, object> task = null;
         lock (items)
         {
             if (items.Count > 0)
             {
                 task = items.Dequeue();
             }
         }
         if (task != null)
         {
             task.Item1(task.Item2);
             if (InnerException != null) // the method threw an exeption
             {
                 throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
             }
         }
         else
         {
             workItemsWaiting.WaitOne();
         }
     }
 }
Ejemplo n.º 13
0
        private void SendCallback(IAsyncResult result)
        {
            Tuple <SocketSendCallback, object> asyncState = (Tuple <SocketSendCallback, object>)result.AsyncState;

            //if (((ISocket)this).IsConnected() == true)
            //{
            try
            {
                this._connection.GetStream().EndWrite(result);
            }
            catch (Exception ex)
            {
                //write failed
            }
            finally
            {
                asyncState.Item1(asyncState.Item2);
            }

            //}
            //else
            //{
            //	lock (_connection)
            //	{
            //		this._connectionDisposed = true;
            //		((ISocket)this).Close();
            //	}
            //}
        }
Ejemplo n.º 14
0
        void Run(object state)
        {
            Tuple <Action, int> data = (Tuple <Action, int>)state;

            Thread.Sleep(data.Item2);
            data.Item1();
        }
Ejemplo n.º 15
0
 public void RunMainLoop()
 {
     do
     {
         Tuple <SendOrPostCallback, object> next = null;
         lock (work) {
             if (work.Count > 0 && !endLoop)
             {
                 next = work.Dequeue();
             }
             else if (!endLoop)
             {
                 Monitor.Wait(work);
             }
         }
         if (next != null)
         {
             try {
                 next.Item1(next.Item2);
             } catch (Exception ex) {
                 Console.WriteLine(ex);
             }
         }
     } while (!endLoop);
 }
Ejemplo n.º 16
0
        public void StartElement(object ctx, string elementName, string[] atts)
        {
            currentAttributeDict = new Dictionary <string, string>();

            if (atts != null && atts[0] != null)
            {
                for (int i = 0; i + 1 < atts.Length; i += 2)
                {
                    string key   = atts[i];
                    string value = atts[i + 1];
                    currentAttributeDict.Add(key, value);
                }
            }

            // Run the action that corresponds to the current element string found in xml file
            Tuple <Action, Action> elementParseActions = null;

            if (mapFileElementActions.TryGetValue(elementName, out elementParseActions))
            {
                // Item 1 of tuple corresponds to begin element action
                elementParseActions.Item1();
            }

            currentAttributeDict = null;
        }
Ejemplo n.º 17
0
        public void OperationCorrectlyHandlesWebExceptionErrors([ValueSource("_operations")] Tuple <Action <TestServiceBase, Uri>, string, bool> operation)
        {
            if (operation.Item3 == false)
            {
                Assert.Inconclusive("Not applicable");
            }
            ;

            // arrange
            var apiUri = ApiRequestHandler.ApiRequestUri;

            var keyService = new SimpleOAuthKeyService()
            {
                OAuthResponse = new OAuthTokens()
                {
                    AccessToken = "<<accesstoken>>", RefreshToken = "<<refreshtoken>>", ExpiresIn = 10
                }
            };
            var factory = new TestWebRequestFactory();

            factory.RegisterResultForUri(OAuthRequestHandler.OAuthRequestUri.AbsoluteUri, new OAuthTokens()
            {
                AccessToken = "<<newaccesstoken>>"
            }.ToJson());
            factory.RegisterExceptionForUri <WebException>(apiUri.AbsoluteUri);

            var service = new TestServiceBase(new ApiConfiguration("<<clientid>>", "<<clientsecret>>", "<<redirecturl>>"), factory, keyService);

            // act
            var ex = Assert.Throws <ApiCommunicationException>(() => operation.Item1(service, apiUri));

            // assert
            Assert.AreEqual(apiUri, ex.URI);
        }
Ejemplo n.º 18
0
 public void BeginMessageLoop()
 {
     while (!_done)
     {
         Tuple <SendOrPostCallback, object> task = null;
         lock (_items)
         {
             if (_items.Count > 0)
             {
                 task = _items.Dequeue();
             }
         }
         if (task != null)
         {
             task.Item1(task.Item2);
             if (InnerException != null)
             {
                 throw InnerException;
             }
         }
         else
         {
             _workItemsWaiting.WaitOne();
         }
     }
 }
Ejemplo n.º 19
0
 public void BeginMessageLoop()
 {
     while (!done)
     {
         Tuple <SendOrPostCallback, object> task = null;
         lock (items)
         {
             if (items.Count > 0)
             {
                 task = items.Dequeue();
             }
         }
         if (task != null)
         {
             task.Item1(task.Item2);
             if (InnerExceptionDispatchInfo != null) // the method threw an exeption
             {
                 InnerExceptionDispatchInfo.Throw();
             }
         }
         else
         {
             workItemsWaiting.WaitOne();
         }
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Generates a report from the provided validation plan by running all the rules against all
        /// arguments. All combinations are reported so rules where types do not match are included but
        /// all evaluate to true (valid).
        /// </summary>
        /// <example>
        /// var report = new { arg1, arg2, ...}.Must()....Report();
        /// </example>
        /// <param name="validationPlan">The validation plan to report on.</param>
        /// <returns>A validation report.</returns>
        /// <exception cref="System.ArgumentNullException">If validationPlan is null.</exception>
        public static ValidationReport Report(this Tuple <GetArguments, IEnumerable <Rule> > validationPlan)
        {
            if (validationPlan == null)
            {
                throw new ArgumentNullException("validationPlan");
            }

            var arguments = validationPlan.Item1();
            var rules     = validationPlan.Item2.ToList();

            var report = arguments.SelectMany(
                _ => rules,
                (argument, rule) =>
            {
                var argumentType  = argument.Item1;
                var argumentName  = argument.Item2;
                var argumentValue = argument.Item3;
                var validate      = rule.Item1;
                var result        = validate(argumentType, argumentValue);

                return(Tuple.Create(argumentType, argumentName, argumentValue, result, rule.Item2, rule.Item3));
            });

            return(report);
        }
Ejemplo n.º 21
0
 public void BeginMessageLoop()
 {
     while (!done)
     {
         Tuple <SendOrPostCallback, object> workItem = null;
         lock (objects)
         {
             if (objects.Count > 0)
             {
                 workItem = objects.Dequeue();
             }
         }
         if (workItem != null)
         {
             workItem.Item1(workItem.Item2);
             if (ObjectException != null)
             {
                 ExceptionDispatchInfo.Capture(ObjectException).Throw();
             }
         }
         else
         {
             pendingObjects.WaitOne();
         }
     }
 }
Ejemplo n.º 22
0
            /// <summary>
            /// Begin message
            /// </summary>
            /// <exception cref="AggregateException"></exception>
            public void BeginMessageLoop()
            {
                while (!this.IsDone)
                {
                    Tuple <SendOrPostCallback, object> task = null;

                    // lock work items
                    lock (this.Items)
                    {
                        if (this.Items.Count > 0)
                        {
                            task = this.Items.Dequeue();
                        }
                    }

                    // is task not null, then invoke it
                    if (task != null)
                    {
                        task.Item1(task.Item2);

                        // the method threw an exeption
                        if (this.InnerException != null)
                        {
                            throw new AggregateException("AsyncHelpers.Run method threw an exception.", this.InnerException);
                        }
                    }
                    else
                    {
                        this.WorkItemsWaiting.WaitOne();
                    }
                }
            }
Ejemplo n.º 23
0
 void Run2(object obj)
 {
     try
     {
         while (_exEvent.Count > 0)
         {
             Tuple <Action <PublishEventArgs>, bool, PublishEventArgs> tmp = null;
             if (_exEvent.TryDequeue(out tmp))
             {
                 if (tmp.Item2)
                 {
                     RunInUiThread(tmp.Item1, tmp.Item3);
                 }
                 else
                 {
                     tmp.Item1(tmp.Item3);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         WriteLog.WriteLogError("EventPublish Run Dispatch Error:" + ex);
     }
 }
Ejemplo n.º 24
0
        public void OperationUpdatesKeyServiceWithNewTokensWhenCurrentTokensHaveExpired([ValueSource("_operations")] Tuple <Action <TestServiceBase, Uri>, string, bool> operation)
        {
            // arrange
            var apiUri = ApiRequestHandler.ApiRequestUri;

            var keyService = new SimpleOAuthKeyService()
            {
                OAuthResponse = new OAuthTokens()
                {
                    AccessToken = "<<accesstoken>>", RefreshToken = "<<refreshtoken>>", ExpiresIn = 10
                }
            };
            var factory = new TestWebRequestFactory();

            factory.RegisterResultForUri(OAuthRequestHandler.OAuthRequestUri.AbsoluteUri, new OAuthTokens()
            {
                AccessToken = "<<newaccesstoken>>"
            }.ToJson());
            factory.RegisterResultForUri(apiUri.AbsoluteUri, operation.Item2);

            var service = new TestServiceBase(new ApiConfiguration("<<clientid>>", "<<clientsecret>>", "<<redirecturl>>"), factory, keyService);

            // act
            operation.Item1(service, apiUri);

            // assert
            Assert.AreEqual("<<newaccesstoken>>", keyService.OAuthResponse.AccessToken);
        }
Ejemplo n.º 25
0
 public void BeginMessageLoop()
 {
     while (!_done)
     {
         Tuple <SendOrPostCallback, object> task = null;
         lock (_items)
         {
             if (_items.Count > 0)
             {
                 task = _items.Dequeue();
             }
         }
         if (task != null)
         {
             task.Item1(task.Item2);
             if (InnerException != null)
             {
                 throw new AggregateException("AsyncExtensions called lambda threw an exception.", InnerException);
             }
         }
         else
         {
             _workItemsWaiting.WaitOne();
         }
     }
 }
Ejemplo n.º 26
0
 public static Tuple <Action, CancellationToken> ToSequence(Tuple <Action, CancellationToken> tuple, Action <CancellationToken> action)
 {
     return new Tuple <Action, CancellationToken>(() =>
     {
         tuple.Item1();
         action(tuple.Item2);
     }, tuple.Item2);
 }
Ejemplo n.º 27
0
        public static byte[] BiserEncodeList <T>(this IEnumerable <T> objs)
        {
            Tuple <Action <Encoder, object>, Func <Decoder, object> > f = GetTypeOfCollection <T>();
            var enc = new Encoder();

            enc.Add(objs, r => { f.Item1(enc, r); });
            return(enc.Encode());
        }
        CreateStringKeyGrainStateQueryExpressionFuncProxy <TGrainState>(
            Tuple <Func <IAddressable, string>, string> arg,
            IAddressable grainRef)
        {
            string grainId = arg.Item1(grainRef);

            return(CreateExpression <TGrainState>(grainId, arg.Item2));
        }
        internal bool Execute(
            bool skipIfNoChanges, bool changesExist, Action <EwfValidation, IEnumerable <string> > validationErrorHandler, bool performValidationOnly = false,
            Tuple <Action, Action> actionMethodAndPostModificationMethod = null)
        {
            var validationNeeded = validations.Any() && (!skipIfNoChanges || changesExist);

            if (validationNeeded)
            {
                var errorsOccurred = false;
                foreach (var validation in validations)
                {
                    var validator = new Validator();
                    validation.Method(validator);
                    if (validator.ErrorsOccurred)
                    {
                        errorsOccurred = true;
                        if (!validator.ErrorMessages.Any())
                        {
                            throw new ApplicationException("Validation errors occurred but there are no messages.");
                        }
                    }
                    validationErrorHandler(validation, validator.ErrorMessages);
                }
                if (errorsOccurred)
                {
                    throw new DataModificationException();
                }
            }

            var skipModification = !modificationMethods.Any() || (skipIfNoChanges && !changesExist);

            if (performValidationOnly || (skipModification && actionMethodAndPostModificationMethod == null))
            {
                return(validationNeeded);
            }

            DataAccessState.Current.DisableCache();
            try {
                if (!skipModification)
                {
                    foreach (var method in modificationMethods)
                    {
                        method();
                    }
                }
                actionMethodAndPostModificationMethod?.Item1();
                DataAccessState.Current.ResetCache();
                AppRequestState.Instance.PreExecuteCommitTimeValidationMethodsForAllOpenConnections();
                actionMethodAndPostModificationMethod?.Item2();
            }
            catch {
                AppRequestState.Instance.RollbackDatabaseTransactions();
                DataAccessState.Current.ResetCache();
                throw;
            }

            return(true);
        }
        public void CompositionTest()
        {
            Lazy <int> functor = new Lazy <int>(() => 1);
            Tuple <Func <Lazy <int>, IEnumerable <int> >, Func <Lazy <int>, IEnumerable <int> > > compositions = this.Compositions <int>();
            IEnumerable <int> x = compositions.Item1(functor);
            IEnumerable <int> y = compositions.Item2(functor);

            Assert.AreEqual(x.Single(), y.Single());
        }
        internal bool Execute(
            bool skipIfNoChanges, bool formValuesChanged, Action<EwfValidation, IEnumerable<string>> validationErrorHandler, bool performValidationOnly = false,
            Tuple<Action, Action> actionMethodAndPostModificationMethod = null)
        {
            var validationNeeded = validations.Any() && ( !skipIfNoChanges || formValuesChanged );
            if( validationNeeded ) {
                var topValidator = new Validator();
                foreach( var validation in validations ) {
                    if( topValidations.Contains( validation ) )
                        validation.Method( AppRequestState.Instance.EwfPageRequestState.PostBackValues, topValidator );
                    else {
                        var validator = new Validator();
                        validation.Method( AppRequestState.Instance.EwfPageRequestState.PostBackValues, validator );
                        if( validator.ErrorsOccurred )
                            topValidator.NoteError();
                        validationErrorHandler( validation, validator.ErrorMessages );
                    }
                }
                if( topValidator.ErrorsOccurred )
                    throw new DataModificationException( Translation.PleaseCorrectTheErrorsShownBelow.ToSingleElementArray().Concat( topValidator.ErrorMessages ).ToArray() );
            }

            var skipModification = !modificationMethods.Any() || ( skipIfNoChanges && !formValuesChanged );
            if( performValidationOnly || ( skipModification && actionMethodAndPostModificationMethod == null ) )
                return validationNeeded;

            DataAccessState.Current.DisableCache();
            try {
                if( !skipModification ) {
                    foreach( var method in modificationMethods )
                        method();
                }
                if( actionMethodAndPostModificationMethod != null )
                    actionMethodAndPostModificationMethod.Item1();
                DataAccessState.Current.ResetCache();
                AppRequestState.Instance.PreExecuteCommitTimeValidationMethodsForAllOpenConnections();
                if( actionMethodAndPostModificationMethod != null )
                    actionMethodAndPostModificationMethod.Item2();
            }
            catch {
                AppRequestState.Instance.RollbackDatabaseTransactions();
                DataAccessState.Current.ResetCache();
                throw;
            }

            return true;
        }
Ejemplo n.º 32
0
 private Action ap_cmb(Tuple<Action, Action> code)
 {
     return delegate() { code.Item1(); code.Item2(); };
 }