Exemple #1
0
 public static IClientMessage GetResult(IFuture <IClientMessage> future, int?timeout = null)
 {
     if (timeout.HasValue)
     {
         return(future.GetResult(timeout.Value));
     }
     return(future.GetResult(TaskOperationTimeOutMilliseconds));
 }
        public void SubmitReturnsFutureThatReturnsResultOfCompletedAction()
        {
            var            runnable = MockRepository.GenerateStub <IRunnable>();
            IFuture <Void> future   = ExecutorService.Submit(runnable);

            future.GetResult();
            runnable.AssertWasCalled(c => c.Run());
            JoinPool(ExecutorService);
        }
Exemple #3
0
            public T Call()
            {
                IFuture <T> ftask = _exec.Submit(_func);

                try
                {
                    return(ftask.GetResult(_duration));
                }
                finally
                {
                    ftask.Cancel(true);
                }
            }
Exemple #4
0
        public static IFuture Bind <T> (this IFuture future, Expression <Func <T> > target)
        {
            var member = BoundMember.New(target);

            future.RegisterOnComplete((_) => {
                Exception error;
                object result;
                if (future.GetResult(out result, out error))
                {
                    ((IBoundMember)member).Value = result;
                }
            });

            return(future);
        }
Exemple #5
0
        public static bool CheckForFailure(this IFuture future, params Type[] failureTypes)
        {
            object    result;
            Exception error;

            if (future.GetResult(out result, out error))
            {
                if (error != null)
                {
                    foreach (Type type in failureTypes)
                    {
                        if (type.IsInstanceOfType(error))
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemple #6
0
 public static ClientMessage GetResult(IFuture <ClientMessage> future, TimeSpan timeout)
 {
     return(future.GetResult((int)timeout.TotalMilliseconds));
 }
Exemple #7
0
 public static ClientMessage GetResult(IFuture <ClientMessage> future, int timeout)
 {
     return(future.GetResult(timeout));
 }
Exemple #8
0
 public static ClientMessage GetResult(IFuture <ClientMessage> future)
 {
     return(future.GetResult(Timeout.Infinite));
 }
Exemple #9
0
        private T DoInvokeAny <T>(IEnumerable tasks, int count, bool timed, TimeSpan durationToWait, Converter <object, IRunnableFuture <T> > converter)
        {
            if (tasks == null)
            {
                throw new ArgumentNullException("tasks");
            }
            List <IFuture <T> >           futures = count > 0 ? new List <IFuture <T> >(count) : new List <IFuture <T> >();
            ExecutorCompletionService <T> ecs     = new ExecutorCompletionService <T>(this);
            TimeSpan duration = durationToWait;

            // For efficiency, especially in executors with limited
            // parallelism, check to see if previously submitted tasks are
            // done before submitting more of them. This interleaving
            // plus the exception mechanics account for messiness of main
            // loop.

            try
            {
                // Record exceptions so that if we fail to obtain any
                // result, we can throw the last exception we got.
                ExecutionException ee       = null;
                DateTime           lastTime = (timed) ? DateTime.Now : new DateTime(0);
                IEnumerator        it       = tasks.GetEnumerator();
                bool hasMoreTasks           = it.MoveNext();
                if (!hasMoreTasks)
                {
                    throw new ArgumentException("No tasks passed in.");
                }
                futures.Add(ecs.Submit(converter(it.Current)));
                int active = 1;

                for (;;)
                {
                    IFuture <T> f = ecs.Poll();
                    if (f == null)
                    {
                        if (hasMoreTasks && (hasMoreTasks = it.MoveNext()))
                        {
                            futures.Add(ecs.Submit(converter(it.Current)));
                            ++active;
                        }
                        else if (active == 0)
                        {
                            break;
                        }
                        else if (timed)
                        {
                            f = ecs.Poll(duration);
                            if (f == null)
                            {
                                throw new TimeoutException();
                            }
                            //TODO: done't understand what are we doing here. Useless!? -K.X.
                            duration = duration.Subtract(DateTime.Now.Subtract(lastTime));
                            lastTime = DateTime.Now;
                        }
                        else
                        {
                            f = ecs.Take();
                        }
                    }
                    if (f != null)
                    {
                        --active;
                        try
                        {
                            return(f.GetResult());
                        }
                        catch (ThreadInterruptedException)
                        {
                            throw;
                        }
                        catch (ExecutionException eex)
                        {
                            ee = eex;
                        }
                        catch (SystemException rex)
                        {
                            ee = new ExecutionException(rex);
                        }
                    }
                }

                if (ee == null)
                {
                    ee = new ExecutionException();
                }
                throw ee;
            }
            finally
            {
                foreach (IFuture <T> future in futures)
                {
                    future.Cancel(true);
                }
            }
        }
 public static IClientMessage GetResult(IFuture<IClientMessage> future, int? timeout = null)
 {
     if (timeout.HasValue) return future.GetResult(timeout.Value);
     return future.GetResult(TaskOperationTimeOutMilliseconds);
 }
 public static IClientMessage GetResult(IFuture<IClientMessage> future, int? timeout = null)
 {
     return future.GetResult(timeout ?? TaskOperationTimeOutMilliseconds);
 }
Exemple #12
0
        static void Main(string[] args)
        {
            IExecutorService executorService = Executors.NewFixedThreadPool(THREAD_POOL_SIZE);

            IFuture <int>    f1 = executorService.Submit <int>(GenerateNumbers);
            IFuture <string> f2 = executorService.Submit <string>(PrintCharacters);
            IFuture <int>    f3 = executorService.Submit <int>(PrintArray);

            Console.WriteLine("Numbers generated till {0}", f1.GetResult());
            Console.WriteLine("Original String {0}", f2.GetResult());
            Console.WriteLine("Array Count {0}", f3.GetResult());


            Console.WriteLine("---------");

            Console.WriteLine("Calculating sums...");

            var futures = new List <IFuture <long> >();

            // Call without method arguments
            for (int i = 0; i < 20000; i++)
            {
                SumNumbers     sumNumbers = new SumNumbers(100 + i);
                IFuture <long> submit     = executorService.Submit <long>(sumNumbers.CalculateSum);
                futures.Add(submit);
            }

            long sum = 0;

            foreach (var future in futures)
            {
                sum += future.GetResult();
            }
            Console.WriteLine("Sum = " + sum);

            futures.Clear();

            Console.WriteLine("---------");

            Console.WriteLine("Calculating sums...");

            // Call with method arguments
            for (int i = 0; i < 20000; i++)
            {
                SumNumbers2    sumNumbers2 = new SumNumbers2();
                int            i1          = i; // copy to local variable for closure.
                IFuture <long> submit      =
                    executorService.Submit(() => sumNumbers2.CalculateSumWithArgsAndReturnValue(100 + i1));
                futures.Add(submit);
            }



            sum = 0;
            foreach (var future in futures)
            {
                sum += future.GetResult();
            }
            Console.WriteLine("Sum = " + sum);


            //Say this was created at runtime and we don't know the type or parameter values at compile time.
            object obj = new SumNumbers2();

            object[] parameters = new object[] { 100 };

            //Find the method we want to invoke
            MethodInfo methodInfo = ReflectionUtils.GetMethod(obj.GetType(),
                                                              "CalculateSumWithArgsAndReturnValue",
                                                              ReflectionUtils.GetTypes(parameters));


            //Use expression trees to generate code to invoke method and assign to a delegate.
            LateBoundMethod methodCallback = DelegateFactory.Create(methodInfo);

            IFuture <object> futureLong = executorService.Submit(() => methodCallback(obj, parameters));
            var result = futureLong.GetResult();

            Console.WriteLine("LateBoundMethod Style : Result = " + result);

            ///Use Spring's IL generation to invoke method dynamically.
            IDynamicMethod method = DynamicMethod.Create(methodInfo);

            IFuture <object> futureLongViaDM = executorService.Submit(() => method.Invoke(obj, parameters));
            var resultViaDM = futureLongViaDM.GetResult();

            Console.WriteLine("Spring's IDynamicMethod Style: Result = " + resultViaDM);


            // This will make the executor accept no new threads
            // and finish all existing threads in the queue
            executorService.Shutdown();


            Console.WriteLine("Hit return to exit");
            Console.ReadLine();
        }