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


C# Task.Wait方法代码示例

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


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

示例1: Beginning

        public static void Beginning()
        {
            // аналоги вызова метода в потоке из ThreadPool
            // Task даёт бОльшую гибкость
            ThreadPool.QueueUserWorkItem(o => LongRunningMethod());
            new Task(LongRunningMethod).Start();
            Task.Run(() => LongRunningMethod());

            Task<int> t = new Task<int>(LongRunningMethodWithResult);
            t.Start(); // запуск задания

            // блокировка вызвавшего потока до завершения задания
            // однако, если задание ещё не выполняется, вызвавший поток может
            // быть назначен исполнителем задания и он не блокируется
            t.Wait();

            // получение результата выполнения задания
            // свойство Result вызывает метод Wait()
            int result = t.Result;

            // выполнение нового задания по завершении предыдущего
            Task newTask = t.ContinueWith(m => Console.WriteLine(t.Result));

            // блокировка вызвавшего потока, пока не завершатся
            // все / хотя бы один метод из параметров
            Task.WaitAll(t);
            Task.WaitAny(t);
        }
开发者ID:tpltn,项目名称:Parallelism,代码行数:28,代码来源:Tasks.cs

示例2: Main

 static void Main(string[] args) {
     Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
     Task t = new Task(() =>
     {
         Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
     });
     t.Start();
     t.Wait();
     Console.ReadLine();
 }
开发者ID:Geronimobile,项目名称:DotNetExamIntro,代码行数:10,代码来源:Program.cs

示例3: Send

 /// <summary>Dispatches a synchronous message to the synchronization context.</summary>
 /// <param name="d">The System.Threading.SendOrPostCallback delegate to call.</param>
 /// <param name="state">The object passed to the delegate.</param>
 public override void Send(SendOrPostCallback d, object state)
 {
     Task t = new Task(() => d(state));
     t.RunSynchronously(_scheduler);
     t.Wait();
 }
开发者ID:Farouq,项目名称:semclone,代码行数:9,代码来源:TaskSchedulerExtensions.cs

示例4: RunBuggySchedulerTests

        public static void RunBuggySchedulerTests()
        {
            Debug.WriteLine("* RunBuggySchedulerTests()");

            BuggyTaskScheduler bts = new BuggyTaskScheduler();
            Task t1 = new Task(delegate { });
            Task t2 = new Task(delegate { });

            //
            // Test Task.Start(buggy scheduler)
            //
            Debug.WriteLine("  -- testing Task.Start(buggy scheduler)");
            try
            {
                t1.Start(bts);
                Assert.True(false, string.Format("    > FAILED.  No exception thrown."));
            }
            catch (TaskSchedulerException)
            {
            }
            catch (Exception e)
            {
                Assert.True(false, string.Format("    > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
            }

            if (t1.Status != TaskStatus.Faulted)
            {
                Assert.True(false, string.Format("    > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status));
            }


            Debug.WriteLine("    -- Waiting on Faulted task (there's a problem if we deadlock)...");
            try
            {
                t1.Wait();
                Assert.True(false, string.Format("    > FAILED.  No exception thrown from Wait()."));
            }
            catch (AggregateException ae)
            {
                if (!(ae.InnerExceptions[0] is TaskSchedulerException))
                {
                    Assert.True(false, string.Format("    > FAILED.  Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name));
                }
            }

            //
            // Test Task.RunSynchronously(buggy scheduler)
            //
            Debug.WriteLine("  -- testing Task.RunSynchronously(buggy scheduler)");
            try
            {
                t2.RunSynchronously(bts);
                Assert.True(false, string.Format("    > FAILED.  No exception thrown."));
            }
            catch (TaskSchedulerException) { }
            catch (Exception e)
            {
                Assert.True(false, string.Format("    > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
            }

            if (t2.Status != TaskStatus.Faulted)
            {
                Assert.True(false, string.Format("    > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status));
            }

            Debug.WriteLine("    -- Waiting on Faulted task (there's a problem if we deadlock)...");
            try
            {
                t2.Wait();
                Assert.True(false, string.Format("    > FAILED.  No exception thrown from Wait()."));
            }
            catch (AggregateException ae)
            {
                if (!(ae.InnerExceptions[0] is TaskSchedulerException))
                {
                    Assert.True(false, string.Format("    > FAILED.  Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name));
                }
            }

            //
            // Test StartNew(buggy scheduler)
            //
            Debug.WriteLine("  -- testing Task.Factory.StartNew(buggy scheduler)");
            try
            {
                Task t3 = Task.Factory.StartNew(delegate { }, CancellationToken.None, TaskCreationOptions.None, bts);
                Assert.True(false, string.Format("    > FAILED.  No exception thrown."));
            }
            catch (TaskSchedulerException) { }
            catch (Exception e)
            {
                Assert.True(false, string.Format("    > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
            }

            //
            // Test continuations
            //
            Debug.WriteLine("  -- testing Task.ContinueWith(buggy scheduler)");
            Task completedTask = Task.Factory.StartNew(delegate { });
            completedTask.Wait();
//.........这里部分代码省略.........
开发者ID:SGuyGe,项目名称:corefx,代码行数:101,代码来源:TaskSchedulerTests.cs


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