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


C# Task.RunSynchronously方法代码示例

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


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

示例1: RunWithSchedulerAsCurrent

 /// <summary>Runs the action with TaskScheduler.Current equal to the specified scheduler.</summary>
 private static void RunWithSchedulerAsCurrent(TaskScheduler scheduler, Action action)
 {
     var t = new Task(action);
     t.RunSynchronously(scheduler);
     t.GetAwaiter().GetResult();
 }
开发者ID:ESgarbi,项目名称:corefx,代码行数:7,代码来源:TaskAwaiterTests.cs

示例2: TryExecuteTaskInline

 /// <summary>Tries to execute the task synchronously on this scheduler.</summary>
 /// <param name="task">The task to execute.</param>
 /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param>
 /// <returns>true if the task could be executed; otherwise, false.</returns>
 protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
 {
     if (_processingTaskOnCurrentThread.Value)
     {
         var t = new Task<bool>(state => TryExecuteTask((Task)state), task);
         t.RunSynchronously(_interleave._parallelOptions.TaskScheduler);
         return t.Result;
     }
     return false;
 }
开发者ID:bingyang001,项目名称:disruptor-net-3.3.0-alpha,代码行数:14,代码来源:ConcurrentExclusiveInterleave.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

示例5: RunSynchronizationContextTaskSchedulerTests

        public static void RunSynchronizationContextTaskSchedulerTests()
        {
            // Remember the current SynchronizationContext, so that we can restore it
            SynchronizationContext previousSC = SynchronizationContext.Current;

            // Now make up a "real" SynchronizationContext abd install it
            SimpleSynchronizationContext newSC = new SimpleSynchronizationContext();
            SetSynchronizationContext(newSC);

            // Create a scheduler based on the current SC
            TaskScheduler scTS = TaskScheduler.FromCurrentSynchronizationContext();

            //
            // Launch a Task on scTS, make sure that it is processed in the expected fashion
            //
            bool sideEffect = false;
            Task task = Task.Factory.StartNew(() => { sideEffect = true; }, CancellationToken.None, TaskCreationOptions.None, scTS);

            Exception ex = null;

            try
            {
                task.Wait();
            }
            catch (Exception e)
            {
                ex = e;
            }

            Assert.True(task.IsCompleted, "Expected task to have completed");
            Assert.True(ex == null, "Did not expect exception on Wait");
            Assert.True(sideEffect, "Task appears not to have run");
            Assert.True(newSC.PostCount == 1, "Expected exactly one post to underlying SynchronizationContext");

            // 
            // Run a Task synchronously on scTS, make sure that it completes
            //
            sideEffect = false;
            Task syncTask = new Task(() => { sideEffect = true; });

            ex = null;
            try
            {
                syncTask.RunSynchronously(scTS);
            }
            catch (Exception e)
            {
                ex = e;
            }

            Assert.True(task.IsCompleted, "Expected task to have completed");
            Assert.True(ex == null, "Did not expect exception on RunSynchronously");
            Assert.True(sideEffect, "Task appears not to have run");
            Assert.True(newSC.PostCount == 1, "Did not expect a new Post to underlying SynchronizationContext");

            //
            // Miscellaneous things to test
            //
            Assert.True(scTS.MaximumConcurrencyLevel == 1, "Expected scTS.MaximumConcurrencyLevel to be 1");

            // restore original SC
            SetSynchronizationContext(previousSC);
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:63,代码来源:TaskSchedulerTests.cs

示例6: AllowsInlineExecutionAfterBeingQueued

            public void AllowsInlineExecutionAfterBeingQueued()
            {
                var executions = 0;
                var taskScheduler = new BlockingThreadPoolTaskScheduler();
                var task = new Task(() => { executions++; }, CancellationToken.None, TaskCreationOptions.AttachedToParent);

                task.RunSynchronously(taskScheduler);

                Assert.Equal(1, executions);
                Assert.Equal(0, taskScheduler.ScheduledTasks.Count());
            }
开发者ID:SparkSoftware,项目名称:infrastructure,代码行数:11,代码来源:BlockingThreadPoolTaskSchedulerTests.cs

示例7: WaitForPreceedingTasksIfRequired

            public void WaitForPreceedingTasksIfRequired()
            {
                var executionOrder = new List<Int32>();
                var tasksQueued = new ManualResetEvent(false);
                var taskScheduler = new PartitionedTaskScheduler();

                Task.Factory.StartNew(() => { executionOrder.Add(0); tasksQueued.WaitOne(); Thread.Sleep(25); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
                Task.Factory.StartNew(() => executionOrder.Add(1), CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);

                var synchronousTask = new Task(() => executionOrder.Add(2), CancellationToken.None, TaskCreationOptions.AttachedToParent);

                tasksQueued.Set();
                synchronousTask.RunSynchronously(taskScheduler);

                Assert.Equal(3, executionOrder.Where((value, index) => value == index).Count());
            }
开发者ID:SparkSoftware,项目名称:infrastructure,代码行数:16,代码来源:PartitionedTaskSchedulerTests.cs

示例8: WillDeadlockIfForceSynchronousExecutionsAcrossPartitions

            public void WillDeadlockIfForceSynchronousExecutionsAcrossPartitions()
            {
                var tasksQueued = new ManualResetEvent(false);
                var partition1Active = new ManualResetEvent(false);
                var partition2Active = new ManualResetEvent(false);
                var task1 = new Task(_ => { }, 1, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
                var task2 = new Task(_ => { }, 2, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
                var taskScheduler = new PartitionedTaskScheduler(task => task.AsyncState, 2, 4);

                var task3 = Task.Factory.StartNew(_ =>
                    {
                        tasksQueued.WaitOne();
                        partition1Active.Set();
                        partition2Active.WaitOne();
                        task1.RunSynchronously();
                    }, 2, CancellationToken.None, TaskCreationOptions.LongRunning, taskScheduler);
                var task4 = Task.Factory.StartNew(_ =>
                    {
                        tasksQueued.WaitOne();
                        partition2Active.Set();
                        partition1Active.WaitOne();
                        task2.RunSynchronously();
                    }, 1, CancellationToken.None, TaskCreationOptions.LongRunning, taskScheduler);

                tasksQueued.Set();

                Assert.False(Task.WaitAll(new[] { task1, task2, task3, task4 }, 100));
            }
开发者ID:SparkSoftware,项目名称:infrastructure,代码行数:28,代码来源:PartitionedTaskSchedulerTests.cs


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