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


C# Task.GetAwaiter方法代码示例

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


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

示例1: GetResultNotCompleted

		public void GetResultNotCompleted ()
		{
			TaskAwaiter awaiter;

			var task = new Task (() => { });
			awaiter = task.GetAwaiter ();

			try {
				awaiter.GetResult ();
				Assert.Fail ();
			} catch (InvalidOperationException) {
			}
		}
开发者ID:sesef,项目名称:mono,代码行数:13,代码来源:TaskAwaiterTest.cs

示例2: GetResultCanceled

		public void GetResultCanceled ()
		{
			TaskAwaiter awaiter;

			var token = new CancellationToken (true);
			var task = new Task (() => { }, token);
			awaiter = task.GetAwaiter ();

			try {
				awaiter.GetResult ();
				Assert.Fail ();
			} catch (TaskCanceledException) {
			}
		}
开发者ID:sesef,项目名称:mono,代码行数:14,代码来源:TaskAwaiterTest.cs

示例3: GetResultFaulted

		public void GetResultFaulted ()
		{
			TaskAwaiter awaiter;

			var task = new Task (() => { throw new ApplicationException (); });
			awaiter = task.GetAwaiter ();
			task.RunSynchronously (TaskScheduler.Current);


			Assert.IsTrue (awaiter.IsCompleted);

			try {
				awaiter.GetResult ();
				Assert.Fail ();
			} catch (ApplicationException) {
			}
		}
开发者ID:sesef,项目名称:mono,代码行数:17,代码来源:TaskAwaiterTest.cs

示例4: WaitOnMainThread

        private static bool WaitOnMainThread(Task task, CancellationToken cancellationToken, int ms) {
            var frame = new DispatcherFrame();
            var resultTask = Task.Run(() => {
                try {
                    return task.Wait(ms, cancellationToken);
                } catch(Exception) {
                    return true;
                } finally {
                    frame.Continue = false;
                }
            });
            Dispatcher.PushFrame(frame);

            if (!resultTask.GetAwaiter().GetResult()) {
                return false;
            }

            task.GetAwaiter().GetResult();
            return true;
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:20,代码来源:TestTaskService.cs

示例5: OperationCanceledException_PropagatesThroughCanceledTask

 public static void OperationCanceledException_PropagatesThroughCanceledTask(int lineNumber, Task task, OperationCanceledException expected)
 {
     var caught = Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult());
     Assert.Same(expected, caught);
 }
开发者ID:ESgarbi,项目名称:corefx,代码行数:5,代码来源:TaskAwaiterTests.cs

示例6: OnSendAsync

        private void OnSendAsync(Task antecedent)
        {
            Contract.Assert(antecedent != null, "Argument 'antecedent' cannot be NULL.");
            this.CancelSendTimer();

            try
            {
                antecedent.GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
                {
                    SocketException socketException = new SocketException(exception.HResult & 0x0000FFFF);
                    _asyncWriteException = ConvertSendException(socketException, TimeSpan.MaxValue);
                }
                else
                {
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }

                    _asyncWriteException = exception;
                }
            }

            this.FinishWrite();
        }
开发者ID:dmetzgar,项目名称:wcf,代码行数:29,代码来源:RTSocketConnection.cs

示例7: FlushWriteImmediate

 private static Task FlushWriteImmediate(Task antecedant, object state)
 {
     antecedant.GetAwaiter().GetResult();
     RTSocketConnection thisPtr = (RTSocketConnection)state;
     return thisPtr._outputStream.FlushAsync(thisPtr._sendCts.Token);
 }
开发者ID:weshaggard,项目名称:wcf,代码行数:6,代码来源:RTSocketConnection.cs

示例8: ContextTest

		public void ContextTest ()
		{
			TaskAwaiter awaiter;

			var task = new Task (() => { throw new ApplicationException (); });
			awaiter = task.GetAwaiter ();
			task.RunSynchronously (TaskScheduler.Current);


			Assert.IsTrue (awaiter.IsCompleted);

			try {
				awaiter.GetResult ();
				Assert.Fail ();
			} catch (ApplicationException) {
			}

			var context = new MyContext ();

			var old = SynchronizationContext.Current;
			SynchronizationContext.SetSynchronizationContext (context);
			try {
				var t = new Task (delegate { });
				var a = t.GetAwaiter ();
				a.OnCompleted (delegate { });
				t.Start ();
				Assert.IsTrue (t.Wait (5000), "#1");
			} finally {
				SynchronizationContext.SetSynchronizationContext (old);
			}

			Assert.IsTrue (context.mre.WaitOne (5000), "#2");
			Assert.AreEqual (1, context.PostCounter, "#3");
		}
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:34,代码来源:TaskAwaiterTest_T.cs

示例9: CompleteTask

 private static void CompleteTask(Task t)
 {
     //observe the result on the main thread, which will propegate execeptions
     sCallbacks.Add(new Tuple<SendOrPostCallback, object>(_ => t.GetAwaiter().GetResult(), null));
     CompleteTask();
 }
开发者ID:AustinWise,项目名称:LibTaskNet,代码行数:6,代码来源:CoopScheduler.cs

示例10: loadRowsAsync

    private void loadRowsAsync()
    {
      subscribeToUserConfigCache(false);

      changeReloadButtonStatus(enabled_: false);

      ProductList.RegisterMongoClasses();

      var userConfigsTask = new Task(() =>
      {
        setStatus("Loading user lists...");
        UserListCache.Instance().RefreshFromServerIfLocalCacheEmpty().Wait();
      });


      var listTask = new Task<IList<SwapsSummaryRow>>(() =>
      {
        subscribeToUserConfigCache();
        ProductList.RegisterMongoClasses();
        setStatus("Pulling DFs from server...");
        DFsCache.Instance().RefreshFromServerIfLocalCacheEmpty().Wait();
        setStatus("Loading tenor dates...");
        TenorDatesCache.Instance().RefreshFromServerIfLocalCacheEmpty().Wait();

        return
          UserListCache.Instance()
            .InnerList.Select(item => new {Config = item, Impl = item.CreateInstrument()})
            .Select(i => new SwapsSummaryRow(i.Impl, i.Config))
            .ToList();
      });

      userConfigsTask.GetAwaiter().OnCompleted(() =>
      {
        profileManageDisplay1.UserListSelected -= handleUserListSelected;

        profileManageDisplay1.Create();
        m_filter.ProfileName = profileManageDisplay1.SelectedProfile;

        profileManageDisplay1.UserListSelected += handleUserListSelected;

        listTask.Start();
      });


      listTask.GetAwaiter().OnCompleted(() =>
      {
        setStatus("Loading structures...");
        var list = listTask.Result;

        ThreadStart finishLoadingGUI = () =>
        {
          setStatus(string.Empty);
          m_originalList = list;
          rebuildWorkingSet();
          m_grid.Create(m_workingSet);
          kickOffLiveSubscriptions();
          changeReloadButtonStatus(enabled_: true);

        };

        if (list.Count == 0)
        {
          finishLoadingGUI();
        }
        else
        {

          try
          {
            Task first = null, prev = null;

            foreach (var item in list)
            {
              var task = new Task(() =>
              {
                item.GetRawStat(StatCols.Values); // kick off stat retrieval
                item.UpdateCentrallyControlledStats();
                //item.SubscribeToLive();
              });

              if (first == null)
                first = task;

              if (prev == null)
                prev = task;
              else
              {
                prev.GetAwaiter().OnCompleted(() =>
                {
                  setStatus(string.Format("Retrieving stats for {0}.{1}", item.Instrument.CurveName, item.Instrument.Description));
                  task.Start();
                });
                prev = task;
              }
            }

            // last one - 
            if (prev != null)
            {
              prev.GetAwaiter().OnCompleted(() =>
//.........这里部分代码省略.........
开发者ID:heimanhon,项目名称:researchwork,代码行数:101,代码来源:MainControl.cs

示例11: ReadBuffer

        // This is the async callback function. Only one thread could/should call this.
        private void ReadBuffer(Task<int> t)
        {
            int byteLen;

            try
            {
                byteLen = t.GetAwaiter().GetResult();
            }
            catch (IOException)
            {
                // We should ideally consume errors from operations getting cancelled
                // so that we don't crash the unsuspecting parent with an unhandled exc. 
                // This seems to come in 2 forms of exceptions (depending on platform and scenario), 
                // namely OperationCanceledException and IOException (for errorcode that we don't 
                // map explicitly).   
                byteLen = 0; // Treat this as EOF
            }
            catch (OperationCanceledException)
            {
                // We should consume any OperationCanceledException from child read here  
                // so that we don't crash the parent with an unhandled exc
                byteLen = 0; // Treat this as EOF
            }

            if (byteLen == 0)
            {
                // We're at EOF, we won't call this function again from here on.
                lock (_messageQueue)
                {
                    if (_sb.Length != 0)
                    {
                        _messageQueue.Enqueue(_sb.ToString());
                        _sb.Length = 0;
                    }
                    _messageQueue.Enqueue(null);
                }

                try
                {
                    // UserCallback could throw, we should still set the eofEvent 
                    FlushMessageQueue();
                }
                finally
                {
                    _eofEvent.Set();
                }
            }
            else
            {
                int charLen = _decoder.GetChars(_byteBuffer, 0, byteLen, _charBuffer, 0);
                _sb.Append(_charBuffer, 0, charLen);
                GetLinesFromStringBuilder();
                _stream.ReadAsync(_byteBuffer, 0, _byteBuffer.Length).ContinueWith(ReadBuffer);
            }
        }
开发者ID:nandhanurrevanth,项目名称:corefx,代码行数:56,代码来源:AsyncStreamReader.cs

示例12: PumpTill

 internal override void PumpTill(Task task)
 {
     task.GetAwaiter().GetResult();
 }
开发者ID:Xarlot,项目名称:Xunit.StaFact,代码行数:4,代码来源:UITestCase.cs

示例13: ValidateFaultedTask

 private static bool ValidateFaultedTask(Task t)
 {
     ((IAsyncResult)t).AsyncWaitHandle.WaitOne();
     bool localPassed = t.IsFaulted;
     try
     {
         t.GetAwaiter().GetResult();
         Debug.WriteLine("     > FAILURE. Faulted task's GetResult should have thrown.");
     }
     catch (Exception e) { localPassed &= ValidateException(e); }
     return localPassed;
 }
开发者ID:jmhardison,项目名称:corefx,代码行数:12,代码来源:AsyncTaskMethodBuilderTests.cs

示例14: ContextTest

		public void ContextTest ()
		{
			var context = new MyContext ();

			var old = SynchronizationContext.Current;
			SynchronizationContext.SetSynchronizationContext (context);
			try {
				var t = new Task (delegate { });
				var a = t.GetAwaiter ();
				a.OnCompleted (delegate { });
				t.Start ();
				Assert.IsTrue (t.Wait (1000), "#1");
			} finally {
				SynchronizationContext.SetSynchronizationContext (old);
			}

			Assert.AreEqual (1, context.PostCounter, "#2");
		}
开发者ID:carrie901,项目名称:mono,代码行数:18,代码来源:TaskAwaiterTest_T.cs

示例15: 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


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