Example #1
1
 private void Begin_Click(object sender, EventArgs e)
 {
     Begin.Text = "开始...";
     Begin.Enabled = false;
     start = true;
     List<Task> listTask = new List<Task>();
     TaskFactory tskf = new TaskFactory();
     var controls = groupBox.Controls;
     foreach (var control in controls)
     {
         if (control.GetType() != typeof(Label))
         {
             continue;
         }
         var label = control as Label;
         listTask.Add(tskf.StartNew(new Action(() =>
         {
             while (start)
             {
                 Thread.Sleep(200);
                 var text = GeNum(label);
                 UpdateLabl(label, text);
                 //Console.WriteLine("label:[{0}],value:[{1}]", label.Name, text);
             }
         })));
     }
     tskf.ContinueWhenAll(listTask.ToArray(), (rest) => { ShowMessage(); });
     //MessageBox.Show("主线程结束了。。。", "结果");
     Thread.Sleep(1000);
     End.Enabled = true;
 }
Example #2
0
        static void Main(string[] args)
        {
            var tf = new TaskFactory(ct);
            var s = tf.StartNew(StoreData, ct);
            var f = tf.StartNew(FetchData, ct);
            var fsi = tf.StartNew(FetchServerInfo, ct);
            var tasks = new[] { s, f, fsi };

            Console.WriteLine("Hit any key to stop.");
            Console.ReadLine();
            cts.Cancel();

            try
            {
                Task.WaitAll(tasks);
            }
            catch (AggregateException ex)
            {
                foreach (var iex in ex.InnerExceptions)
                {
                    var msg = string.Format("[ChaosMonkeyApp] tasks canceled (ex: {0})", iex.Message);
                    Console.WriteLine(msg);
                }
            }
            catch (TaskCanceledException ex)
            {
                var msg = string.Format("[ChaosMonkeyApp] tasks canceled (ex: {0})", ex.Message);
                Console.WriteLine(msg);
            }

            cluster.Dispose();
            cts.Dispose();
            Console.WriteLine("Stopped.");
        }
        public static void Main()
        {
            Task<Int32[]> parent = Task.Run(() =>
            {
                var results = new Int32[3];

                TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent,
                    TaskContinuationOptions.ExecuteSynchronously);

                tf.StartNew(() => results[0]);
                tf.StartNew(() => results[1]);
                tf.StartNew(() => results[2]);

                return results;
            });

            var finalTask = parent.ContinueWith(
                parentTask =>
                {
                    foreach (int i in parentTask.Result)
                        Console.WriteLine(i);
                });

            finalTask.Wait();
        }
Example #4
0
        public static void Do()
        {
            Task<int[]> parent = Task.Run(() =>
            {
                var result = new int[3];

                TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
                tf.StartNew(() => result[0] = 0);
                tf.StartNew(() => result[1] = 1);
                tf.StartNew(() => { Thread.Sleep(3000); result[2] = 2; });

                return result;
            });

            var finalTask = parent.ContinueWith(parentTask =>
            {
                Console.WriteLine(parentTask.Status);
                foreach (var val in parentTask.Result)
                {
                    Console.WriteLine(val);
                }
            });

            finalTask.Wait();
            ;
        }
Example #5
0
        public static void LaunchThread()
        {
            Task<Int32[]> parent = new Task<int[]>(() =>
            {
                var results = new Int32[3];
                // Use this factory configuration...
                TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
                // ... to create tasks
                tf.StartNew(() => results[0] = 4);
                tf.StartNew(() => results[1] = 5);
                tf.StartNew(() => results[2] = 6);
                return results;
            });

            parent.Start();

            var finalTask = parent.ContinueWith(
            parentTask =>
            {
                foreach (int i in parentTask.Result)
                    Console.WriteLine(i);
            });

            // Wait the task parent finished (and the child tasks finished)
            finalTask.Wait();

            // Result :
            // 4
            // 5
            // 6
            Console.ReadKey();
        }
        public static void Run()
        {
            Console.WriteLine(@"Task Factory Example: Start");

            var parent = Task.Run(() =>
            {
                var results = new Int32[3];

                var taskFactory = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);

                taskFactory.StartNew(() => results[0] = 0);

                taskFactory.StartNew(() => results[1] = 1);

                taskFactory.StartNew(() => results[2] = 2);

                return results;
            });

            var finalTask = parent.ContinueWith(parentTask => 
            {
                foreach (var i in parentTask.Result)
                {
                    Console.WriteLine(i);
                }
            });

            finalTask.Wait();

            Console.WriteLine(@"Task Factory Example: Stop");
        }
        public static void Main(string[] args)
        {
            Task<int[]> parent = Task.Run(() =>
                {
                    var results = new int[3];

                    TaskFactory factory = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);

                    factory.StartNew(() => results[0] = 0);
                    factory.StartNew(() => results[1] = 1);
                    factory.StartNew(() => results[2] = 2);

                    return results;
                });

            var finalTask = parent.ContinueWith(
                parentTask =>
                {
                    foreach (var i in parentTask.Result)
                    {
                        Console.WriteLine(i);
                    }
                });

            finalTask.Wait();

            Console.ReadLine();
        }
        public void Disabled_Test_TaskScheduler_Basic ()
        {
            var sequentialTaskScheduler = new SequentialTaskScheduler (
                "TestScheduler"
                );
    
            var taskFactory = new TaskFactory (sequentialTaskScheduler);

            var usageCount = 0;

            var stopwatch = new Stopwatch ();
            
            stopwatch.Start ();

            var firstTask = taskFactory.StartNew (() => {Thread.Sleep (500); ++usageCount;});
            var secondTask = taskFactory.StartNew (() => {Thread.Sleep (500); ++usageCount;});

            firstTask.Wait ();
            secondTask.Wait ();

            stopwatch.Stop ();

            TestFor.Equality(2, usageCount, "Both tasks are expected to be executed");
            TestFor.Equality(true, Math.Abs(stopwatch.ElapsedMilliseconds - 1000) < 100, "Elapsed time is expected to be around 1 sec");

            sequentialTaskScheduler.DisposeNoThrow();
        }
Example #9
0
        static void Main(string[] args)
        {
            Task<Int32[]> parent = Task.Run(() =>
                {
                    var results = new Int32[3];
                    TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
                    tf.StartNew(() => results[0] = 0);
                    tf.StartNew(() => results[1] = 1);
                    tf.StartNew(() => results[2] = 2);

                    return results;
                });

            var finalTask = parent.ContinueWith(
                parentTask =>
                {
                    foreach (int i in parentTask.Result)
                    {
                        Console.WriteLine(i);
                    }
                });

            finalTask.Wait();
            Console.Write("Press a key to exit");
            Console.ReadKey();
        }
        public BlockingDataReader(IDataReader reader, Predicate<IDataReader> readWhile = null)
        {
            _Reader = reader;

            var f = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);

            _LoadDataRows = f.StartNew(() => LoadingWork(readWhile));
            _MapIntoTuples = f.StartNew(() => MapDataRows());
        }
Example #11
0
        public static void Main()
        {
            Task<Int32[]> t = Task<Int32[]>.Run(() =>
            {
                int i;

                var result = new Int32[3];

                new Task(() =>
                {
                    result[0] = 1;
                }, TaskCreationOptions.AttachedToParent);
                new Task(() =>
                {
                    result[1] = 2;
                }, TaskCreationOptions.AttachedToParent);
                new Task(() =>
                {
                    result[2] = 3;
                }, TaskCreationOptions.AttachedToParent);

                TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent,TaskContinuationOptions.AttachedToParent);
                tf.StartNew(() => {
                    Thread.Sleep(1000);
                    result[0] = 1;
                });
                tf.StartNew(() =>
                {
                    Thread.Sleep(2000);
                    result[1] = 2;
                });

                tf.StartNew(() =>
                {
                    Thread.Sleep(3000);
                    result[2] = 3;
                });

                return result;

            });
            Task.WaitAll(t);
            t.ContinueWith((parenttask) =>
            {
                foreach (var item in parenttask.Result)
                {
                    Console.WriteLine(item.ToString());
                }
            });

            Console.Read();
        }
Example #12
0
        /// <summary>
        /// MutiThreading process with Tasks.
        /// </summary>
        private static void ProcessTasksWithMutiThreads()
        {
            Random r = new Random();
            TaskCount = 1000;
            int maximumNum = 10;

            List<Task> tasks = new List<Task>();
            var taskFactory = new TaskFactory();

            while (TaskCount > 0)
            {
                Console.WriteLine("==========================================");
                if (tasks.Count < maximumNum)
                {
                    tasks.Add(taskFactory.StartNew(() =>
                    {
                        int sleepTime = r.Next(3, 15);
                        Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - Sleep " + sleepTime + " seconds..");
                        Thread.Sleep(sleepTime * 1000);
                        TaskCount--;
                    }));
                }
                else
                {
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - Wait for tasks to complete.");
                    Task.WaitAll(tasks.ToArray());
                    tasks = tasks.Where(t => !t.IsCompleted && !t.IsCanceled && t.IsFaulted).ToList();
                }
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - #Tasks:" + tasks.Count);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - " + TaskCount + " tasks completed.");
                Console.WriteLine("==========================================");
            }
        }
Example #13
0
        static void Main(string[] args)
        {
            Func<int> doSomething = () =>
            {
                var x = new Random().Next(26);
                Debug.WriteLine((char)(97 + x));
                Trace.TraceWarning("Anything. More detail go here.");
                Trace.TraceError("Error. More detail go here.");
                Trace.WriteLine("This is writeline.", "Category");
                Trace.TraceInformation("Just some information");
                return 0;
            };
            const int count = 500;

            TaskFactory<int> factory = new TaskFactory<int>(TaskCreationOptions.PreferFairness, TaskContinuationOptions.LongRunning);//so I have more threads
            List<Task> tasks = new List<Task>(count);
            Console.WriteLine("{0:s} Before task loop.", DateTimeOffset.Now);
            Debug.WriteLine(string.Format("{0:s} Before task loop.", DateTimeOffset.Now));
            for (int i = 0; i < count; i++)
            {
                tasks.Add(factory.StartNew(doSomething));
            };
            Console.WriteLine("{0:s} After task loop.", DateTimeOffset.Now);
            Debug.WriteLine(string.Format("{0:s} After task loop.", DateTimeOffset.Now));
            Task.WaitAll(tasks.ToArray(), System.Threading.Timeout.Infinite);//so now we have a long mail message queue.
            Console.WriteLine("{0:s} After wait all.", DateTimeOffset.Now);
            Debug.WriteLine(string.Format("{0:s} After wait all.", DateTimeOffset.Now));
            Console.ReadLine();
        }
Example #14
0
        private static void Run4Common()
        {
            var tasksCount = 10;
            _log.Debug("任务调度开始……");

            var taskFactory = new TaskFactory();
            var cts = new CancellationTokenSource();
            var tasks = new Task<string>[10];

            for (var i = 0; i < tasksCount; i++)
            {
                var i1 = i;
                tasks[i] =
                taskFactory.StartNew(() => Handler(new TaskArgs
                {
                    CancellationToken = cts.Token,
                    Name = i1.ToString(CultureInfo.InvariantCulture)
                }), cts.Token);
            }

            //TaskContinuationOptions.None 有异常会 中断。。。。
            taskFactory.ContinueWhenAll(tasks, CompleteCallback, TaskContinuationOptions.None);

            _log.Debug("任务调度完成……");

        }
Example #15
0
        public void StartStrategy()
        {
            IsStarted = true;

            IEnumerable<Candle> candles = from c in candleRepository.Get()
                                      where c.TickerId == Instr.Ticker.Id && c.TimeFrameId == Instr.TimeFrame.Id && c.DateOpen >= DateFrom && c.DateOpen < DateTo
                                      orderby c.DateOpen
                                      select c;

            TaskFactory factory = new TaskFactory(cts.Token);
            factory.StartNew(() =>
            {
                foreach (Candle candle in candles)
                {
                    if (cts.Token.IsCancellationRequested) //выход из потока по кнопке "Стоп"
                        return;

                    //вызвать событие формирования свечи
                    Instr.Candles.Insert(0, candle);
                    Instr.OnCreatedCandle();
                    Instr.OnCreatedCandleAsync();

                    Strategy.Begin();
                }
                IsStarted = false;
            }
            );

        }
Example #16
0
 public void ParallelStressLoad()
 {
     var start = DateTime.Now;
     var factory = new TaskFactory();
     var tasks = new Task[20];
     for (var t = 0; t < tasks.Length; ++t)
     {
         tasks[t] = factory.StartNew(() =>
         {
             var client = new SecurityTokenServiceClient();
             var tokens = new string[20];
             for (int au = 0; au < tokens.Length; ++au)
             {
                 var token = client.Add(new[] { new KeyValuePair<string, string>("id", au.ToString()) });
                 tokens[au] = token;
                 for (int gu = 0; gu < au; ++gu)
                 {
                     var user = client.Get(tokens[gu]);
                     Assert.AreEqual(gu.ToString(), user.First(item => item.Key == "id").Value);
                 }
             }
         });
     }
     Console.WriteLine("tasks created");
     Task.WaitAll(tasks);
     var finish = DateTime.Now;
     var elapsed = finish - start;
     Console.WriteLine(elapsed);
 }
Example #17
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
            {
                await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
            }

            if (Frame.CanGoBack)
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
            else
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;

            eqLogic = e.Parameter as EqLogic;
            ActionList = eqLogic.GetActionsCmds();
            InformationList = eqLogic.GetInformationsCmds();
            EqLogicName = eqLogic.name;
            if (ActionList.Count == 0)
                actionview.Visibility = Visibility.Collapsed;

            if (InformationList.Count == 0)
                infoview.Visibility = Visibility.Collapsed;

            var taskFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
            await taskFactory.StartNew(() => DoWork(tokenSource), tokenSource.Token);

            base.OnNavigatedTo(e);
        }
        public void ShouldSend100MessagesMultiThreadedWithTransactions()
        {
            int count = 100;
            var stop = Stopwatch.StartNew();
            using (var provider = new XmsProducerProvider(true))
            {
                var taskFactory = new TaskFactory();
                var tasks = new Task[count];

                for (int i = 0; i < count; i++)
                {
                    tasks[i] = taskFactory.StartNew(
                        () =>
                        {
                            using(var scope = new TransactionScope(TransactionScopeOption.Required))
                            {
                                provider.SendTestMessage(destination);
                                scope.Complete();
                            }
                        });
                }
                Task.WaitAll(tasks.ToArray());
                stop.Stop();
            }
            Console.WriteLine("Sent {0} messages multi-threaded in {1}", count, stop.Elapsed);
            destination.AssertMessageCount(count);
        }
        public void ShouldRead100MessagesMultiThreaded()
        {
            int expected = 100;
            destination.FillWith(expected);
            
            var stop = Stopwatch.StartNew();
            using (var provider = new XmsConsumerProvider(false))
            {
                var taskFactory = new TaskFactory();
                var tasks = new Task[expected];

                for (int i = 0; i < expected; i++)
                {
                    tasks[i] = taskFactory.StartNew(
                        () =>
                            {
                                using(var consumer = provider.GetConsumer(destination))
                                {
                                    var message = consumer.ReceiveNoWait();
                                    if (message != null) Interlocked.Increment(ref actual);
                                }
                            });
                }
                Task.WaitAll(tasks.ToArray());
                stop.Stop();
            }
            Console.WriteLine("Received {0} messages multi-threaded in {1}", expected, stop.Elapsed);
            Assert.That(actual, Is.EqualTo(expected));
        }
Example #20
0
        public override void Run(string[] args) {
            /*
             * 1. 获取RevokedApp,以200为一组
             * 2. 从Search API上找数据,找到的可复活
             * 3. 对于找到的数据
             *    3.1. 添加一条Resurrect类型的更新信息
             *    3.2. 从RevokeApp中移除
             *    3.3. 新增到App中
             *    
             * XXX: 一次Rescue任务不会复活太多的应用,从详细日志里能看到数量,不实现计数功能了
             */
            Stopwatch watch = new Stopwatch();

            logger.Info("Start rescue task");
            watch.Start();

            // 从数据库分批取
            TaskFactory factory = new TaskFactory();
            List<Tasks.Task> tasks = new List<Tasks.Task>();
            for (int i = 0; i < settings.ParallelDegree; i++) {
                Tasks.Task task = factory.StartNew(RetrieveAndRescue);
                tasks.Add(task);
            }
            Tasks.Task.WaitAll(tasks.ToArray());

            watch.Stop();
            logger.Info("Finished task using {0}", watch.Elapsed);
        }
        public void TaskToObservable_NonVoid_Complete_BeforeCreate()
        {
            var taskScheduler = new TestTaskScheduler();
            var taskFactory = new TaskFactory(taskScheduler);
            var res = default(ITestableObserver<int>);

            taskFactory.StartNew(() =>
            {
                var scheduler = new TestScheduler();

                var taskSource = new TaskCompletionSource<int>();
                taskSource.Task.ContinueWith(t => { var e = t.Exception; });

                scheduler.ScheduleAbsolute(10, () => taskSource.SetResult(42));

                res = scheduler.Start(() =>
                    taskSource.Task.ToObservable()
                );
            });

            res.Messages.AssertEqual(
                OnNext(200, 42),
                OnCompleted<int>(200)
            );
        }
Example #22
0
        static void Main()
        {
            const int numberTasks = 2;
            const int partitionSize = 1000000;
            var data = new List<string>(FillData(partitionSize * numberTasks));

            var barrier = new Barrier(numberTasks + 1);

            var taskFactory = new TaskFactory();
            var tasks = new Task<int[]>[numberTasks];
            for (int i = 0; i < numberTasks; i++)
            {
                tasks[i] = taskFactory.StartNew<int[]>(CalculationInTask,
                    Tuple.Create(i, partitionSize, barrier, data));
            }

            barrier.SignalAndWait();
            var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) =>
                {
                    return c1 + c2;
                });

            char ch = 'a';
            int sum = 0;
            foreach (var x in resultCollection)
            {
                Console.WriteLine("{0}, count: {1}", ch++, x);
                sum += x;
            }

            Console.WriteLine("main finished {0}", sum);
            Console.WriteLine("remaining {0}, phase {1}", barrier.ParticipantsRemaining, barrier.CurrentPhaseNumber);

        }
Example #23
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Retention example started.");
            trace.TraceEvent(TraceEventType.Information, 1001, "Retention example started.");

            int numberOfTasks = 16;
            int messagesPerTask = 100;

            Action sendMessages = () =>
            {
                var batchGuid = Guid.NewGuid();
                Console.WriteLine("{0:s} Batch {1} started.", DateTimeOffset.Now, batchGuid);
                for (int i = 0; i < messagesPerTask; i++)
                {
                    trace.TraceEvent(TraceEventType.Warning, 3000 + i, "Warning {0} - {1}", i, batchGuid);
                }
                Console.WriteLine("{0:s} Batch {1} finished.", DateTimeOffset.Now, batchGuid);
            };

            var factory = new TaskFactory();
            var tasks = new List<Task>(numberOfTasks);
            Console.WriteLine("{0:s} Before task loop.", DateTimeOffset.Now);
            for (int i = 0; i < numberOfTasks; i++)
            {
                tasks.Add(factory.StartNew(sendMessages));
            };
            Console.WriteLine("{0:s} After task loop.", DateTimeOffset.Now);

            Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(10));
            Console.WriteLine("{0:s} Finished (after wait all).", DateTimeOffset.Now);

            trace.TraceEvent(TraceEventType.Information, 8001, "Filtering example stopped.");
            Console.ReadLine();
        }
Example #24
0
        protected override void StartTasks(TaskFactory factory, CancellationToken token)
        {
            /* Create a single loop on the thread */
            Action singleLoop = () =>
            {
                Machine.Current.Boot();

                OnStatusChange(this.Status, EngineStatus.Running);

                while (true)
                {
                    Begin();

                    /* Execute a step in the CPU */
                    Machine.Current.DeviceCPU.StepOnce();

                    /* Run compare core */
                    if (Machine.Current.MipsCompareEngine != null)
                        Machine.Current.MipsCompareEngine.Run();

                    End();
                }
            };

            RuntimeHelpers.PrepareDelegate(singleLoop);

            factory.StartNew(singleLoop, token);
        }
 private static Task<HttpResponseMessage> Login() {
     var taskFactory = new TaskFactory<HttpResponseMessage>();
     return taskFactory.StartNew(() => {
         var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
         response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=\"any user and password\""));
         return response;
     });
 }
Example #26
0
 public static void Run3()
 {
     CancellationTokenSource cts = new CancellationTokenSource();
     //等待按下任意一个键取消任务
     TaskFactory taskFactory = new TaskFactory();
     Task[] tasks = new Task[]
         {
             taskFactory.StartNew(() => Add(cts.Token)),
             taskFactory.StartNew(() => Add(cts.Token)),
             taskFactory.StartNew(() => Add(cts.Token))
         };
     //CancellationToken.None指示TasksEnded不能被取消
     taskFactory.ContinueWhenAll(tasks, TasksEnded, CancellationToken.None);
     Console.ReadKey();
     cts.Cancel();
     Console.ReadKey();
 }
    public static void Main(){
        Task parent = new Task(() => 
	    {
                var cts = new CancellationTokenSource ();
                var tf  = new TaskFactory<Int32> (cts.Token, 
						  TaskCreationOptions.AttachedToParent,
                                                  TaskContinuationOptions.ExecuteSynchronously, 
						  TaskScheduler.Default);

                // This task creates and starts 3 child tasks
                var childTasks = new[] {
                    tf.StartNew(() => Sum(cts.Token, 10000)),
                    tf.StartNew(() => Sum(cts.Token, 20000)),
                    tf.StartNew(() => Sum(cts.Token, Int32.MaxValue))  // Too big, throws OverflowException
                };

                // If any of the child tasks throw, cancel the rest of them
                for (Int32 task = 0; task < childTasks.Length; task++)
                    childTasks[task].ContinueWith (t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);

                // When all children are done, get the maximum value returned from the
                // non-faulting/canceled tasks. Then pass the maximum value to another
                // task that displays the maximum result
                tf.ContinueWhenAll (childTasks, completedTasks => completedTasks.Where(t => t.Status == TaskStatus.RanToCompletion).Max(t => t.Result), 
                                    CancellationToken.None)
                .ContinueWith(t =>Console.WriteLine("The maximum is: " + t.Result),
                              TaskContinuationOptions.ExecuteSynchronously);
            });

        // When the children are done, show any unhandled exceptions too
        parent.ContinueWith(p => {
                // I put all this text in a StringBuilder and call Console.WriteLine just once
                // because this task could execute concurrently with the task above & I don't
                // want the tasks' output interspersed
                StringBuilder sb = new StringBuilder(
                    "The following exception(s) occurred:" + Environment.NewLine);

                foreach (var e in p.Exception.Flatten().InnerExceptions)
                    sb.AppendLine("   "+ e.GetType().ToString());
                Console.WriteLine(sb.ToString());
            }, TaskContinuationOptions.OnlyOnFaulted);

        // Start the parent Task so it can start its children
        parent.Start();
        Thread.Sleep(1000);
    }
Example #28
0
 public static void AddTask(TaskBase task, TaskScheduler scheduler)
 {
     if (_mainUiScheduler == null)
         _mainUiScheduler = scheduler;
     TaskFactory taskFactory = new TaskFactory(_mainUiScheduler);
     Task A = taskFactory.StartNew(task.Run);
     Task B = A.ContinueWith(t => {  }, _mainUiScheduler);
 }
 private void PublishUsingMultipleThreads(int threads, int perThread)
 {
     var factory = new TaskFactory();
     var options = TaskCreationOptions.LongRunning;
     var tasks = (from i in Enumerable.Range(0, threads)
                  select factory.StartNew(() => PublishUsingSingleThread(perThread), options));
     Task.WaitAll(tasks.ToArray());
 }
Example #30
0
 private void loginButton_Click(object sender, RoutedEventArgs e) {
     loginButton.Content = "Login In...";
     TaskFactory tf = new TaskFactory();
     tf.StartNew(() => {
         this.Dispatcher.Invoke(() => {
             doLogin();
         });
     });
 }
Example #31
0
        static int Main(string[] args)
        {
            stopwatch.Restart();

            if (args.Length != 4)
            {
                PrintUsage();
                return(1);
            }

            Assembly.Load("GeneratedCode");

            using (var connection = ConnectWithReceptionist(args[1], Convert.ToUInt16(args[2]), args[3]))
            {
                var channel = new Channel(FirestoreClient.DefaultEndpoint.Host, FirestoreClient.DefaultEndpoint.Port, GoogleCredential.FromFile(Path.Combine(Directory.GetCurrentDirectory(), CloudFirestoreInfo.GoogleCredentialFile)).ToChannelCredentials());
                var task    = FirestoreDb.CreateAsync(CloudFirestoreInfo.FirebaseProjectId, FirestoreClient.Create(channel));

                var connected = true;
                SpatialOSConnectionSystem.connection = connection;

                var dispatcher = new Dispatcher();

                dispatcher.OnDisconnect(op =>
                {
                    Console.Error.WriteLine("[disconnect] " + op.Reason);
                    connected = false;
                });

                CloudFirestoreInfo.Database = task.Result;

                var factory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);

                factory.StartNew(ResourcesInventorySystem.UpdateLoop);
                factory.StartNew(ResourceGeneratorSystem.UpdateLoop);
                factory.StartNew(ResourceExtractorSystem.UpdateLoop);

                stopwatch.Stop();

                connection.SendLogMessage(LogLevel.Info, "Initialization", string.Format("Init Time {0}ms", stopwatch.Elapsed.TotalMilliseconds.ToString("N0")));

                while (connected)
                {
                    stopwatch.Restart();

                    using (var opList = connection.GetOpList(100))
                    {
                        Parallel.Invoke(
                            () => dispatcher.Process(opList),
                            () => PositionsSystem.ProccessOpList(opList),
                            () => IdentificationsSystem.ProccessOpList(opList),
                            () => ResourcesInventorySystem.ProccessOpList(opList),
                            () => ResourceGeneratorSystem.ProccessOpList(opList),
                            () => ResourceExtractorSystem.ProccessOpList(opList)
                            );
                    }

                    SpatialOSConnectionSystem.Update();

                    stopwatch.Stop();
                }

                SpatialOSConnectionSystem.connection = null;

                channel.ShutdownAsync().Wait();
            }

            return(1);
        }