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


C# TaskCompletionSource类代码示例

本文整理汇总了C#中TaskCompletionSource的典型用法代码示例。如果您正苦于以下问题:C# TaskCompletionSource类的具体用法?C# TaskCompletionSource怎么用?C# TaskCompletionSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults

        public void ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true };
            HttpResponseMessage response = new HttpResponseMessage();
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response);
            tcs.TrySetException(exception);
            mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task);
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);
            Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" },
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "ExecuteAuthorizationFilterAsync" }
            };

            // Act & Assert
            Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:31,代码来源:AuthorizationFilterTracerTest.cs

示例2: ConnectAsync

 public Task<Socket> ConnectAsync(IPEndPoint remoteEndPoint)
 {
     _connectTcs = new TaskCompletionSource<Socket>();
     var task = _connectTcs.Task;
     Connect(remoteEndPoint);
     return task;
 }
开发者ID:SaladLab,项目名称:Akka.Interfaced.SlimSocket,代码行数:7,代码来源:TcpConnector.cs

示例3: SaveServerCreds

        private async Task<bool> SaveServerCreds(ServerCredentials configuration)
        {
            var tsc = new TaskCompletionSource<bool>();
            Deployment.Current.Dispatcher.BeginInvoke(async () =>
            {
                await Lock.WaitAsync();

                try
                {
                    var json = JsonConvert.SerializeObject(configuration);

                    await _storageService.WriteAllTextAsync(Constants.Settings.ServerCredentialSettings, json).ConfigureAwait(false);
                }
                finally
                {
                    Lock.Release();
                }

                Debug.WriteLine("SaveCreds, Server count: " + (configuration != null && configuration.Servers != null ? configuration.Servers.Count : 0));

                tsc.SetResult(true);
            });

            return await tsc.Task;
        }
开发者ID:gep13,项目名称:Emby.WindowsPhone,代码行数:25,代码来源:CredentialProvider.cs

示例4: CopyToAsync

 public Task CopyToAsync(Stream stream)
 {
     if (stream == null) {
         throw new ArgumentNullException("stream");
     }
     var tcs = new TaskCompletionSource<object>();
     try {
         var task = this.SerializeToStreamAsync(stream);
         if (task == null) {
             throw new InvalidOperationException();
         }
         task.ContinueWith(t => {
             if (t.IsFaulted) {
                 tcs.TrySetException(t.Exception.GetBaseException());
                 return;
             }
             if (t.IsCanceled) {
                 tcs.TrySetCanceled();
                 return;
             }
             tcs.TrySetResult(null);
         });
     }
     catch (Exception ex) {
         tcs.TrySetException(ex);
     }
     return tcs.Task;
 }
开发者ID:beginor,项目名称:System_Net_Http,代码行数:28,代码来源:HttpContent.cs

示例5: Execute

        public static Task<ResponseMessage> Execute(this WebClient client,
                                                    RequestMessage requestMessage,
                                                    Uri uri,
                                                    string productName,
                                                    TaskCompletionSource<string> tcs) {
            client.ShouldNotBeNull("client");
            requestMessage.ShouldNotBeNull("requestMessage");

            try {
                var responseText = ResolveRequestSerializer(productName).Serialize(requestMessage).Base64Encode();

                return
                    client
                        .UploadStringTask(uri, "POST", responseText)
                        .ContinueWith(task => {
                                          var responseBytes = task.Result;
                                          return ResolveResponseSerializer(productName).Deserialize(responseBytes.Base64Decode());
                                      });
            }
            catch(Exception ex) {
                if(log.IsErrorEnabled)
                    log.ErrorException("WebClient를 통한 요청이 실패했습니다.", ex);

                throw;
            }
        }
开发者ID:debop,项目名称:NFramework,代码行数:26,代码来源:ClientTool.WebClient.cs

示例6: GetStringAsync

        /// <summary>
        /// Get the string by URI.
        /// </summary>
        /// <param name="requestUri">The Uri the request is sent to.</param>
        /// <returns>string</returns>
        public Task<string> GetStringAsync(Uri requestUri)
        {
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

            try
            {
                this.DownloadStringCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        tcs.TrySetResult(e.Result);
                    }
                    else
                    {
                        tcs.TrySetException(e.Error);
                    }
                };

                this.DownloadStringAsync(requestUri);

            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            if (tcs.Task.Exception != null)
            {
                throw tcs.Task.Exception;             
            }

            return tcs.Task;
        }
开发者ID:philoushka,项目名称:PodcastToYouTube,代码行数:38,代码来源:HttpClient.cs

示例7: AsAsyncResult

        /// <summary>
        /// A helper method for mocking APM (classic) asynchronous methods with on TAP (modern) asynchronous methods.
        /// </summary>
        /// <remarks>
        /// This is based on <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx"/> 
        /// and <a href="http://msdn.microsoft.com/en-us/library/hh873178.aspx"/>.
        /// </remarks>
        public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
        {
            Debug.Assert(task != null, "task");

            var taskCompletionSource = new TaskCompletionSource<object>(state);
            task.ContinueWith(
                t =>
                {
                    if (t.IsFaulted)
                    {
                        taskCompletionSource.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else
                    {
                        taskCompletionSource.SetResult(null);
                    }

                    if (callback != null)
                    {
                         callback(taskCompletionSource.Task);
                    }
                },
                TaskScheduler.Default);

            return taskCompletionSource.Task;
        }
开发者ID:bitstadium,项目名称:HockeySDK-Windows,代码行数:37,代码来源:TaskExtensions.cs

示例8: DoWork

		private Task<bool> DoWork(
			DoWorkArguments arguments)
		{
			Console.WriteLine("{0:mm:ss.ffffff} [{1}] Doing work for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
			var _result = new TaskCompletionSource<bool>();

			new Task(() =>
				{
					Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Starting for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
					Thread.Sleep(arguments.SleepInterval);

					if (arguments.ShouldThrowException)
					{
						Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Sequence {2} is exceptional !", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
						var _exception = new ApplicationException("Bang !");
						_result.SetException(_exception);
					}
					else
					{
						_result.SetResult(arguments.ResultToReturn);
					}
					Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Completed for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
				}).Start();

			Console.WriteLine("{0:mm:ss.ffffff} [{1}] Exiting for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
			return _result.Task;
		}
开发者ID:pmcgrath,项目名称:PMCG.Messaging,代码行数:27,代码来源:TaskInv2.cs

示例9: SignIn

		async Task<bool> SignIn()
		{
			var tcs = new TaskCompletionSource<bool> ();
			var alert = new UIAlertView ("Please sign in", "", null, "Cancel", "Ok");
			alert.AlertViewStyle = UIAlertViewStyle.SecureTextInput;
			var tb = alert.GetTextField(0);
			tb.ShouldReturn = (t)=>{

				alert.DismissWithClickedButtonIndex(1,true);
				signIn(tcs,tb.Text);
				return true;
			};

			alert.Clicked += async (object sender, UIButtonEventArgs e) => {
				if(e.ButtonIndex == 0)
				{
					tcs.TrySetResult(false);
					alert.Dispose();
					return;
				}

				var id = tb.Text;
				signIn(tcs,id);
			
			
			};
			alert.Show ();
			return await tcs.Task;
		}
开发者ID:nagyist,项目名称:iPadPos,代码行数:29,代码来源:PaymentViewController.cs

示例10: InteractDuringBrowse

        public async Task InteractDuringBrowse() {
            using (var debugSession = new DebugSession(_session)) {
                using (var sf = new SourceFile("x <- 'old'; browser()")) {
                    var browse = new TaskCompletionSource<bool>();
                    debugSession.Browse += (s, e) => {
                        browse.TrySetResult(true);
                    };

                    await sf.Source(_session);
                    await browse.Task;

                    using (var inter = await _session.BeginInteractionAsync()) {
                        await inter.RespondAsync("x <- 'new'\n");
                    }

                    REvaluationResult x;
                    using (var eval = await _session.BeginEvaluationAsync()) {
                        x = await eval.EvaluateAsync("x");
                    }

                    x.StringResult.Should().Be("new");
                }
            }

        }
开发者ID:AlexanderSher,项目名称:RTVS-Old,代码行数:25,代码来源:DebugReplTest.cs

示例11: RunMultipleTasksWithSingleResult

		public Task<bool> RunMultipleTasksWithSingleResult()
		{
			var _result = new TaskCompletionSource<bool>();

			var _arguments = new []
				{
					new DoWorkArguments { Sequence = 1, SleepInterval = TimeSpan.FromMilliseconds(5000), ResultToReturn = false, ShouldThrowException = false },
					new DoWorkArguments { Sequence = 2, SleepInterval = TimeSpan.FromMilliseconds(25), ResultToReturn = true, ShouldThrowException = true },
					new DoWorkArguments { Sequence = 3, SleepInterval = TimeSpan.FromMilliseconds(50), ResultToReturn = true, ShouldThrowException = false }
				};
			
			var _tasks = new List<Task<bool>>();
			Parallel.ForEach(_arguments, argument => _tasks.Add(this.DoWork(argument)));

			Task.WhenAll(_tasks).ContinueWith(taskResults =>
				{
					Console.WriteLine("{0:mm:ss.ffffff} [{1}] ---> Processing result ({2})", DateTime.Now, Thread.CurrentThread.ManagedThreadId, taskResults.Status);
					if (taskResults.IsFaulted)
					{
						_result.SetException(taskResults.Exception);
					}
					else
					{
						var _allGood = taskResults.Result.All(result => result);
						_result.SetResult(_allGood);
					}
				});

			Console.WriteLine("{0:mm:ss.ffffff} [{1}] About to return task completion result", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
			return _result.Task;
		}
开发者ID:pmcgrath,项目名称:PMCG.Messaging,代码行数:31,代码来源:TaskInv2.cs

示例12: IsEventEditableForTest

        public async Task IsEventEditableForTest()
        {
            var tcs = new TaskCompletionSource<Event>();
            string userId = "u1";
            string userId2 = "u2";
            Guid e1Id = new Guid("00000000-0000-0000-0000-000000000000");
            Guid e2Id = new Guid("00000000-0000-0000-0000-000000000001");
            Event e1 = new Event { Id = e1Id, Title = "New Event", OthersCanEdit = true };
            Event e2 = new Event { Id = e2Id, Title = "New Event2", OthersCanEdit = false, OrganizerId = userId };
            tcs.SetResult(e1);

            _eventRepository.Setup(mock => mock.GetEventInfo(e1Id)).Returns(tcs.Task);
            var task = await _userService.IsEventEditableFor(e1Id, userId);
            _eventRepository.Verify(mock => mock.GetEventInfo(e1Id), Times.Once());
            Assert.AreEqual(true, task, "This event should be editable, but the method IsEventEditable returns false.");

            var tcs2 = new TaskCompletionSource<Event>();
            tcs2.SetResult(e2);
            _eventRepository.Setup(mock => mock.GetEventInfo(e2Id)).Returns(tcs2.Task);
            var task2 = await _userService.IsEventEditableFor(e2Id, userId);
            _eventRepository.Verify(mock => mock.GetEventInfo(e2Id), Times.Once(), "Method GetEventInfo was not called or was called more than once (or its parameters were wrong).");
            Assert.AreEqual(true, task2, "This event should be editable, but the method IsEventEditable returns false.");

            _eventRepository.Setup(mock => mock.GetEventInfo(e2Id)).Returns(tcs2.Task);
            var task3 = await _userService.IsEventEditableFor(e2Id, userId2);
            _eventRepository.Verify(mock => mock.GetEventInfo(e2Id), Times.Exactly(2), "Method GetEventInfo was not called or was called more than once (or its parameters were wrong).");
            Assert.AreEqual(false, task3, "This event should not be editable, but the method IsEventEditable returns true.");
        }
开发者ID:tomaskristof,项目名称:event-planner,代码行数:28,代码来源:UserServiceTests.cs

示例13: OnActivityResult

        static int PICK_CONTACT_REQUEST = 42; // The request code
        
        protected void OnActivityResult(TaskCompletionSource<ContactInfo> tcs, ActivityResultEventArgs e) //int requestCode, Android.App.Result resultCode, Intent data)
        {
            // Check which request it is that we're responding to
            if (e.requestCode == PICK_CONTACT_REQUEST)
            {
                // Make sure the request was successful
                if (e.resultCode == Android.App.Result.Ok)
                {
                    var loader = new CursorLoader(MainActivity.Instance, e.data.Data, projection, null, null, null);
                    var cursor = (Android.Database.ICursor)loader.LoadInBackground();

                    var contactList = new List<ContactInfo>();
                    if (cursor.MoveToFirst())
                    {
                        do
                        {
                            contactList.Add(GetContactInfoFromCursor(cursor));
                        } while (cursor.MoveToNext());
                    }
                    tcs.SetResult(contactList.FirstOrDefault());
                    return;
                }
            }

            tcs.SetResult(null);
        }
开发者ID:BillWagner,项目名称:MobileKidsIdApp,代码行数:28,代码来源:ContactPicker.cs

示例14: CreateNewInstance

 public override IChannelHandler CreateNewInstance()
 {
     // TODO correct? shares references...
     var tcsRconResponse = new TaskCompletionSource<Message.Message>(_tcsRconResponse.Task.AsyncState);
     var tcsResponse = new TaskCompletionSource<Message.Message>(_tcsResponse.Task.AsyncState);
     return new RconInboundHandler(tcsRconResponse, tcsResponse);
 }
开发者ID:pacificIT,项目名称:TomP2P.NET,代码行数:7,代码来源:RconInboundHandler.cs

示例15: SendAsync

 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
     CancellationToken cancellationToken)
 {
     TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
     tcs.SetResult(new HttpResponseMessage());
     return tcs.Task;
 }
开发者ID:Choulla-Naresh8264,项目名称:google-api-dotnet-client,代码行数:7,代码来源:ConfigurableMessageHandlerTest.cs


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