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


C# Task.RunSynchronously方法代码示例

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


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

示例1: Run

        protected virtual void Run(Action<Func<bool>> runAction, bool async) {
            // New task, increment id;
            Interlocked.Increment(ref _taskId);

            // Do not run multiple tasks. According to http://msdn.microsoft.com/en-us/library/dd270681.aspx
            // task can only be disposed if it is RanToCompletion, Faulted, or Canceled.
            // If task is not in one of those states, we queue it for disposal later.

            // Note that task may actually still be running since it may not be able to
            // cancel immediately. The important part is that we don't care about its results.
            // This means that task we no longer care about can still signal completion and 
            // we should ignore it. We use taskId member to determine if task calling is 
            // the current task.

            SignalTaskBegins();

            _task = new Task((taskId) => {
                try {
                    Func<bool> isCancelledCallback = () => { return IsCancellationRequested() || (TaskId != (long)taskId); };
                    runAction(isCancelledCallback);
                } catch (Exception) { } finally { }
            }, TaskId);

            if (!async) {
                _task.RunSynchronously();
                DisposeTask();
            } else {
                _task.Start();
            }
        }
开发者ID:AlexanderSher,项目名称:RTVS-Old,代码行数:30,代码来源:CancellableTask.cs

示例2: QueueTask

 public void QueueTask(ITask task)
 {
     Task newTask = new Task(delegate () {
         task.Execute();
     });
     newTask.RunSynchronously(this);
 }
开发者ID:maxrogoz,项目名称:COSystemArchitect,代码行数:7,代码来源:TaskQueue.cs

示例3: Run

 public override void Run()
 {
     /*
     _storeName = "single-thread-test";
     if (_client.DoesStoreExist(_storeName))
     {
         _client.DeleteStore(_storeName);
     }
     _client.CreateStore(_storeName);
      */
     var importTask = new Task(AddData);
     for (int i = 0; i < 5; i++)
     {
         var queryTask = new Task(QueryData);
         _queryTasks.Add(queryTask);
         queryTask.Start();
     }
     importTask.RunSynchronously();
     _endQueries = true;
     Task.WaitAll(_queryTasks.ToArray());
     if (File.Exists("querytimes.txt")) File.Delete("querytimes.txt");
     using(var writer= new StreamWriter(File.OpenWrite("querytimes.txt")))
     {
         foreach(var qt in _queryTimes)
         {
             writer.WriteLine("{0},{1}", qt.Item1, qt.Item2);
         }
         writer.Close();
     }
     Console.WriteLine("Ran {0} queries during import. Query times written to querytimes.txt", _queryTimes.Count);
 }
开发者ID:Garwin4j,项目名称:BrightstarDB,代码行数:31,代码来源:SingleThreadStressTest.cs

示例4: ShouldNotFreakOutWhenItCantLookUpAWord

        public void ShouldNotFreakOutWhenItCantLookUpAWord()
        {
            //Arrange

            var task = new Task<HttpResponseMessage>(() => new HttpResponseMessage
            {
                Content = new StringContent("{" +
                                            "    \"word\": \"stub\"," +
                                            "    \"definition\": \"Sorry, boet, this_word_is_almost_guaranteed_not_to_exist_if_only_I_had_mocks_and_stuff_reach is not defined in this dictionary.\"" +
                                            "}")

            });

            task.RunSynchronously();
            _transport.Setup(x => x.GetAsync(It.IsAny<string>()))
                .Returns(task);
            var service = new RailsLookupService(()=>_transport.Object);
            var word = "this_word_is_almost_guaranteed_not_to_exist_if_only_I_had_mocks_and_stuff_reach";
            //Act
            Task<string> lookup = service.Lookup(word);
            var result = lookup;

            //Assert
            Assert.AreEqual(string.Format(NotFoundText, word), result.Result);
        }
开发者ID:OryxGazella,项目名称:ifkam-dictionary,代码行数:25,代码来源:LookupServiceTests.cs

示例5: TryExecuteTaskInline

			protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
			{
				if (task.Status != TaskStatus.Created)
					return false;

				task.RunSynchronously (scheduler.target);
				return true;
			}
开发者ID:nzaugg,项目名称:mono,代码行数:8,代码来源:ConcurrentExclusiveSchedulerPair.cs

示例6: RunSynchronously

        //-----------------------------------------------------------------------------------
        // Executes the task synchronously (on the current thread).
        //

        internal Task RunSynchronously(TaskScheduler taskScheduler)
        {
            Debug.Assert(taskScheduler == TaskScheduler.Default, "PLINQ queries can currently execute only on the default scheduler.");
            TraceHelpers.TraceInfo("[timing]: {0}: Running work synchronously", DateTime.Now.Ticks, _taskIndex);
            Task task = new Task(s_runTaskSynchronouslyDelegate, this, TaskCreationOptions.AttachedToParent);
            task.RunSynchronously(taskScheduler);
            return task;
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:12,代码来源:QueryTask.cs

示例7: Configure

        protected override void Configure()
        {
            container = new PhoneContainer();

#if DEBUG
            LogManager.GetLog = type => new DebugLogger(type);
#endif

            container.RegisterPhoneServices(RootFrame);

            var initTasks = new Task(() => PerformAsyncInitializationsAsync());
            initTasks.RunSynchronously();

            container.RegisterPerRequest(typeof(IConfigurationService), null, typeof(DefaultConfigurationService));
            container.RegisterPerRequest(typeof(IDataService), null, typeof(DefaultDataService));
            container.RegisterPerRequest(typeof(ILocationService), null, typeof(DefaultLocationService));
            container.RegisterPerRequest(typeof(IUIService), null, typeof(DefaultUIService));

            // container.RegisterPerRequest(typeof(IEchtzeitdatenService), null, typeof(CreateCampEchtzeitdatenService));
            container.RegisterPerRequest(typeof(IEchtzeitdatenService), null, typeof(OgdEchtzeitdatenService));
            container.RegisterPerRequest(typeof(IRoutingService), null, typeof(OgdRoutingService));

            container.PerRequest<MainPageViewModel>();
            container.PerRequest<MenuViewModel>();
            container.PerRequest<TrafficInfoViewModel>();
            container.PerRequest<FavoritesViewModel>();

            container.PerRequest<StationsPivotPageViewModel>();
            container.PerRequest<StationsListViewModel>();
            container.PerRequest<StationsSearchViewModel>();
            container.PerRequest<NearbyStationsViewModel>();

            container.PerRequest<LinesPivotPageViewModel>();
            container.PerRequest<MetroViewModel>();
            container.PerRequest<TramViewModel>();
            container.PerRequest<BusViewModel>();
            container.PerRequest<NightBusViewModel>();

            container.PerRequest<LineInfoPageViewModel>();

            container.PerRequest<MapNearbyStationsPageViewModel>();

            container.PerRequest<StationInfoPivotPageViewModel>();
            container.PerRequest<DepartureViewModel>();

            container.PerRequest<RoutingPageViewModel>();
            container.PerRequest<NewRouteViewModel>();
            container.PerRequest<StationSelectorViewModel>();
            container.PerRequest<RouteHistoryViewModel>();

            container.PerRequest<TripsViewModel>();

            container.PerRequest<SettingsPageViewModel>();
            container.PerRequest<AboutPageViewModel>();

            AddCustomConventions();
        }
开发者ID:vijayalakshmik,项目名称:viennarealtime,代码行数:57,代码来源:AppBootstrapper.cs

示例8: ChangeInterval

 /// <summary>
 /// Function to set timer time to specific time.
 /// </summary>
 /// <param name="timer">Object of type Timer</param>
 /// <param name="dueTime">Timer due time</param>
 /// <param name="period">Timer due period</param>
 /// <returns>True or false</returns>
 public static bool ChangeInterval(this Timer timer, int dueTime, int period)
 {
     using (var task = new Task(() => timer.Change(dueTime, period)))
     {
         task.RunSynchronously();
         LogException(task.Exception);
         return !task.IsFaulted;
     }
 } 
开发者ID:JaipurAnkita,项目名称:mastercode,代码行数:16,代码来源:TimerExtensions.cs

示例9: TryExecuteTaskInlineExecutesTaskSynchronously

        public void TryExecuteTaskInlineExecutesTaskSynchronously()
        {
            int taskThreadId = 0;
            var task = new Task(() => { taskThreadId = Thread.CurrentThread.ManagedThreadId; });

            task.RunSynchronously(new CurrentThreadTaskScheduler());

            Assert.Equal(Thread.CurrentThread.ManagedThreadId, taskThreadId);
        }
开发者ID:ZeoAlliance,项目名称:ApplicationInsights-dotnet,代码行数:9,代码来源:CurrentThreadTaskSchedulerTest.cs

示例10: TryExecuteTaskInline

        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }

            task.RunSynchronously();
            return true;
        }
开发者ID:atanasmihaylov,项目名称:lanscan,代码行数:10,代码来源:TestTaskScheduler.cs

示例11: RunSynchronously

		public void RunSynchronously ()
		{
			var aTask = new Task (() => {
				/* Do Something */
				IsSet = true;
				Thread.Sleep (1);
			});

			aTask.RunSynchronously ();
		}
开发者ID:caloggins,项目名称:DOT-NET-on-Linux,代码行数:10,代码来源:TaskExample.cs

示例12: Lookup

 public Task<string> Lookup(string word)
 {
     var output = "this word you speak of I have not found";
     if (_dictionary.ContainsKey(word))
     {
          output = _dictionary[word];
     }
     var task = new Task<string>(() => output);
     task.RunSynchronously();
     return task;
 }
开发者ID:OryxGazella,项目名称:ifkam-dictionary,代码行数:11,代码来源:LocalLookupService.cs

示例13: BasicRunSynchronouslyTest

		public void BasicRunSynchronouslyTest ()
		{
			bool ran = false;
			var t = new Task (() => ran = true);

			t.RunSynchronously ();
			Assert.IsTrue (t.IsCompleted);
			Assert.IsFalse (t.IsFaulted);
			Assert.IsFalse (t.IsCanceled);
			Assert.IsTrue (ran);
		}
开发者ID:phucdat1d,项目名称:mono,代码行数:11,代码来源:TaskSchedulerTest.cs

示例14: Case1

        static void Case1()
        {
            Task task = new Task(() =>
            {
                Console.WriteLine("i am a task. thread id:{0}", Thread.CurrentThread.ManagedThreadId);
            });

            //task.Start();//异步执行
            task.RunSynchronously();//同步执行

            Console.WriteLine("main thread id:{0}", Thread.CurrentThread.ManagedThreadId);
        }
开发者ID:0iron0,项目名称:Simon.Asynchronous.Demo,代码行数:12,代码来源:TaskDemo.cs

示例15: Synchronize_GetVersionsAndGetReturnDuplicateEntries_RemovesDuplicates

    public async Task Synchronize_GetVersionsAndGetReturnDuplicateEntries_RemovesDuplicates ()
    {
      var builder = new SynchronizerBuilder();

      builder.AtypeIdComparer = StringComparer.InvariantCultureIgnoreCase;

      builder.AtypeRepository
          .Expect (r => r.GetVersions())
          .IgnoreArguments()
          .Return (
              Task.FromResult<IReadOnlyList<EntityIdWithVersion<string, string>>> (
                  new[] { EntityIdWithVersion.Create ("A1", "v1"), EntityIdWithVersion.Create ("a1", "v3") }));

      builder.BtypeRepository
          .Expect (r => r.GetVersions())
          .IgnoreArguments()
          .Return (
              Task.FromResult<IReadOnlyList<EntityIdWithVersion<string, string>>> (
                  new[] { EntityIdWithVersion.Create ("b1", "v2") }));


      Task<IReadOnlyList<EntityWithVersion<string, string>>> aTypeLoadTask = new Task<IReadOnlyList<EntityWithVersion<string, string>>> (
          () => new List<EntityWithVersion<string, string>> { EntityWithVersion.Create ("A1", "AAAA"), EntityWithVersion.Create ("a1", "____") });
      aTypeLoadTask.RunSynchronously();
      builder.AtypeRepository
          .Expect (r => r.Get (Arg<ICollection<string>>.Matches (c => c.Count == 1 && c.First() == "A1")))
          .Return (aTypeLoadTask);

      Task<IReadOnlyList<EntityWithVersion<string, string>>> bTypeLoadTask = new Task<IReadOnlyList<EntityWithVersion<string, string>>> (
          () => new List<EntityWithVersion<string, string>> { EntityWithVersion.Create ("b1", "BBBB"), });
      bTypeLoadTask.RunSynchronously();
      builder.BtypeRepository
          .Expect (r => r.Get (Arg<ICollection<string>>.Matches (c => c.Count == 1 && c.First() == "b1")))
          .Return (bTypeLoadTask);


      var knownData = new EntityRelationData<string, string, string, string> ("A1", "v1", "b1", "v2");
      builder.InitialEntityMatcher
          .Expect (m => m.FindMatchingEntities (null, null, null, null, null))
          .IgnoreArguments()
          .Return (new List<IEntityRelationData<string, string, string, string>> { knownData });

      builder.InitialSyncStateCreationStrategy
          .Expect (s => s.CreateFor_Unchanged_Unchanged (knownData))
          .Return (new DoNothing<string, string, string, string, string, string> (knownData));

      var synchronizer = builder.Build();
      await synchronizer.Synchronize();

      builder.EntityRelationDataAccess.AssertWasCalled (
          c => c.SaveEntityRelationData (Arg<List<IEntityRelationData<string, string, string, string>>>.Matches (l => l.Count == 1 && l[0] == knownData)));
    }
开发者ID:rafaelriedel,项目名称:outlookcaldavsynchronizer,代码行数:52,代码来源:SynchronizerFixture.cs


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