当前位置: 首页>>代码示例>>C#>>正文


C# TaskFactory.StartNew方法代码示例

本文整理汇总了C#中TaskFactory.StartNew方法的典型用法代码示例。如果您正苦于以下问题:C# TaskFactory.StartNew方法的具体用法?C# TaskFactory.StartNew怎么用?C# TaskFactory.StartNew使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在TaskFactory的用法示例。


在下文中一共展示了TaskFactory.StartNew方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Begin_Click

 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;
 }
开发者ID:s455016457,项目名称:study,代码行数:31,代码来源:Form1.cs

示例2: Main

        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();
        }
开发者ID:nissbran,项目名称:Training-Certifications,代码行数:28,代码来源:Program.cs

示例3: Disabled_Test_TaskScheduler_Basic

        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();
        }
开发者ID:mrange,项目名称:T4Include,代码行数:27,代码来源:TestsFor_TaskSchedulers.cs

示例4: Do

        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();
            ;
        }
开发者ID:JobiJoba,项目名称:70-483,代码行数:26,代码来源:TaskParentFactory.cs

示例5: Main

        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();
        }
开发者ID:jimadybobalon,项目名称:Programming-in-C-,代码行数:25,代码来源:Program.cs

示例6: LaunchThread

        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();
        }
开发者ID:general03,项目名称:70-483,代码行数:32,代码来源:TaskChildFactory.cs

示例7: Run

        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");
        }
开发者ID:ehouarn-perret,项目名称:EhouarnPerret.CSharp.MS.Exam70483,代码行数:31,代码来源:Example5TaskFactory.cs

示例8: Main

        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();
        }
开发者ID:jbijoux,项目名称:Exam70_483,代码行数:26,代码来源:Program.cs

示例9: Main

        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.");
        }
开发者ID:basho,项目名称:riak-dotnet-client,代码行数:34,代码来源:Program.cs

示例10: BlockingDataReader

        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());
        }
开发者ID:AlienEngineer,项目名称:ConcurrentReader,代码行数:9,代码来源:BlockingDataReader.cs

示例11: Main

        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();
        }
开发者ID:vijaychandar1989,项目名称:70-483_Samples,代码行数:52,代码来源:Task2.cs

示例12: Main

        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();
        }
开发者ID:amccool,项目名称:essentialdiagnostics,代码行数:29,代码来源:Program.cs

示例13: ShouldSend100MessagesMultiThreadedWithTransactions

        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);
        }
开发者ID:sasha-uk,项目名称:NServiceBus.Xms.2,代码行数:27,代码来源:XmsProducerProviderTest.cs

示例14: ParallelStressLoad

 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);
 }
开发者ID:Cognite-Soft,项目名称:ARB_2016_V2,代码行数:29,代码来源:StsTests.cs

示例15: TaskToObservable_NonVoid_Complete_BeforeCreate

        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)
            );
        }
开发者ID:Ziriax,项目名称:Rx.NET,代码行数:25,代码来源:TaskObservableExtensionsTest.cs


注:本文中的TaskFactory.StartNew方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。