コード例 #1
0
        public static Task InvokeAsync([NotNull] this IDispatcherService service, [NotNull] Func<Task> action)
        {
            Guard.NotNull(service, nameof(service));
            Guard.NotNull(action, nameof(action));

            var tcs = new TaskCompletionSource();

            service.InvokeAsync(new Action(() =>
            {
                action().ContinueWith(t =>
                {
                    if (t.Exception != null)
                    {
                        tcs.TrySetException(t.Exception);
                        return;
                    }

                    if (t.IsCanceled)
                    {
                        tcs.TrySetCanceled();
                    }

                    tcs.TrySetResult();
                });
            }));

            return tcs.Task;
        }
コード例 #2
0
ファイル: AsyncFactory.cs プロジェクト: Lakerfield/AsyncEx
 private static AsyncCallback Callback(Action<IAsyncResult> endMethod, TaskCompletionSource<object> tcs)
 {
     return asyncResult =>
     {
         try
         {
             endMethod(asyncResult);
             tcs.TrySetResult(null);
         }
         catch (OperationCanceledException)
         {
             tcs.TrySetCanceled();
         }
         catch (Exception ex)
         {
             tcs.TrySetException(ex);
         }
     };
 }
コード例 #3
0
ファイル: APM_EAP.cs プロジェクト: andrekiba/KLabAsyncAwait
        private static Task<string> DumpWebPageAsync(WebClient client, Uri uri)
        {
            //si utilizza TaskCompletionSource che gestisce un task figlio
            var tcs = new TaskCompletionSource<string>();

            DownloadStringCompletedEventHandler handler = null;

            handler = (sender, args) =>
            {
                client.DownloadStringCompleted -= handler;

                if (args.Cancelled)
                    tcs.TrySetCanceled();
                else if (args.Error != null)
                    tcs.TrySetException(args.Error);
                else
                    tcs.TrySetResult(args.Result);
            };

            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(uri);

            return tcs.Task;
        }
コード例 #4
0
 public void TrySetResult_CompletesTask()
 {
     Test.Async(async () =>
     {
         var tcs = new TaskCompletionSource();
         tcs.TrySetResult();
         await tcs.Task;
     });
 }
コード例 #5
0
 /// <summary>
 /// Attempts to transition the underlying <see cref="Task"/> into the <see cref="TaskStatus.RanToCompletion"/> state.
 /// </summary>
 /// <returns><c>true</c> if the operation was successful; otherwise, <c>false</c>.</returns>
 public bool TrySetResult()
 {
     return(_tcs.TrySetResult(null));
 }
コード例 #6
0
ファイル: FacebookService.cs プロジェクト: fadafido/tojeero
		private Task<FacebookUser> getUserData(Facebook.CoreKit.AccessToken token)
		{
			var fbUser = new FacebookUser()
				{
					Token = token.TokenString,
					ExpiryDate = token.ExpirationDate.ToDateTime()
				};

			var completion = new TaskCompletionSource<FacebookUser>();

			var request = new GraphRequest("me", NSDictionary.FromObjectAndKey(new NSString("id, first_name, last_name, email, location"), new NSString("fields")), "GET");
			request.Start((connection, result, error) =>
				{					
					if(error != null)
					{
						Mvx.Trace(MvxTraceLevel.Error, error.ToString());
					}
					else
					{
						
						var data = NSJsonSerialization.Serialize(result as NSDictionary, 0, out error);
						if(error != null)
						{
							Mvx.Trace(MvxTraceLevel.Error, error.ToString());
						}
						else
						{
							var json = new NSString(data, NSStringEncoding.UTF8).ToString();
							fbUser.User = JsonConvert.DeserializeObject<User>(json);
							fbUser.User.ProfilePictureUrl =  string.Format("https://graph.facebook.com/{0}/picture?width={1}&height={1}", fbUser.User.ID, Constants.FBProfilePicSize);
						}
						completion.TrySetResult(fbUser);	
					}

				});
			return completion.Task;
		}
コード例 #7
0
        protected override async Task HandleAudioVideoCall(CallReceivedEventArgs<AudioVideoCall> args, CancellationToken cancellationToken)
        {
            try
            {
                // only new conversations supported
                if (!args.IsNewConversation)
                    return;

                // locate destination application URI
                var uri = applications.GetOrDefault(new RealTimeAddress(args.Call.Conversation.LocalParticipant.Uri));
                if (uri == null)
                    throw new Exception(string.Format("No configured Application for {0}.", args.Call.Conversation.LocalParticipant.Uri));

                // signals activation of flow
                var active = new TaskCompletionSource();

                // subscribe to flow configuration requested
                args.Call.AudioVideoFlowConfigurationRequested += (s, a) =>
                {
                    // subscribe to flow state changes
                    if (a.Flow != null)
                        a.Flow.StateChanged += (s2, a2) =>
                        {
                            if (a2.PreviousState != MediaFlowState.Active &&
                                a2.State == MediaFlowState.Active)
                                Dispatch(() =>
                                {
                                    active.TrySetResult();
                                });
                        };
                };

                // accept the call and wait for an active flow
                await args.Call.AcceptAsync();
                await active.Task;

                // initiate browser
                using (var browser = new Browser())
                {
                    var result = new TaskCompletionSource<VoiceXmlResult>();
                    browser.SessionCompleted += (s3, a3) => OnSessionCompleted(result, a3);
                    browser.Disconnecting += (s3, a3) => OnDisconnecting(result, a3);
                    browser.Disconnected += (s3, a3) => OnDisconnected(result, a3);
                    browser.Transferring += (s3, a3) => OnTransferring(result, a3);
                    browser.Transferred += (s3, a3) => OnTransfered(result, a3);
                    browser.SetAudioVideoCall(args.Call);
                    browser.RunAsync(uri, null);
                    await result.Task;
                }
            }
            catch (Exception e)
            {
                OnUnhandledException(new ExceptionEventArgs(e, ExceptionSeverityLevel.Error));
            }
        }