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


C# TaskCompletionSource.TrySetResult方法代码示例

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


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

示例1: SetSwitch

        public static Task<bool> SetSwitch(LightSwitch ls, bool on)
        {
            var urlBuilder = new StringBuilder(BaseUrl + "wemo/");
            var action = on ? "on/" : "off/";
            urlBuilder.Append(action);
            urlBuilder.Append(ls.Name);
            urlBuilder.Append("?nocache=" + Environment.TickCount.ToString());

            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += (s, args) =>
            {
                if (args.Error != null)
                {
                    tcs.TrySetResult(false);
                }
                else
                {
                    if (string.Compare(args.Result, "OK", StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        tcs.TrySetResult(true);
                    }
                    else
                    {
                        tcs.TrySetResult(false);
                    }
                }
            };
            wc.DownloadStringAsync(new Uri(urlBuilder.ToString(), UriKind.Absolute));

            return tcs.Task;
        }
开发者ID:pierreca,项目名称:HomeControllerApp,代码行数:33,代码来源:HomeControllerApi.Lights.cs

示例2: Request

        public Task<ResponseData> Request(RequestData request, CancellationToken _)
        {
            var cancellation = new CancellationTokenSource(this.timeout);

            var responseTask = this.client.Request(request, cancellation.Token);

            var completion = new TaskCompletionSource<ResponseData>();

            //when the token reaches timeout, tries to set the timeoutResponse as the result
            //if the responseTask already completed, this is ignored
            cancellation.Token.Register(() => completion.TrySetResult(this.timeoutResponse));

            //when the responseTask completes, tries to apply its exception/result properties as long as the timeout isn't reached
            responseTask.ContinueWith(t =>
            {
                if (!cancellation.IsCancellationRequested)
                {
                    if (responseTask.Exception != null)
                    {
                        completion.TrySetException(responseTask.Exception.InnerException);
                    }
                    else
                    {
                        completion.TrySetResult(responseTask.Result);
                    }
                }
            });

            return completion.Task;
        }
开发者ID:yonglehou,项目名称:ServiceProxy,代码行数:30,代码来源:TimeoutClient.cs

示例3: GetAwaiter

 public static TaskAwaiter<bool> GetAwaiter(this IShowableViewModel vmModel)
 {
     var tcs = new TaskCompletionSource<bool>();
     vmModel.Closed += (s, e) => tcs.TrySetResult(false);
     if (vmModel.IsClosed) tcs.TrySetResult(false);
     return tcs.Task.GetAwaiter();
 }
开发者ID:ikit-mita,项目名称:ikit-mita-frameworks,代码行数:7,代码来源:ViewModelExtensions.cs

示例4: GoToState

        public static Task<bool> GoToState(this Control control, string state)
        {
            var taskSource = new TaskCompletionSource<bool>();
            var layoutRoot = VisualTreeHelper.GetChild(control, 0) as FrameworkElement;
            var visualStateGroups = VisualStateManager.GetVisualStateGroups(layoutRoot);
            var visualState = visualStateGroups.OfType<VisualStateGroup>().SelectMany(i => i.States.OfType<VisualState>()).FirstOrDefault(i => i.Name == state);

            if (visualState == null)
                throw new ArgumentException("VisualState wasn't found");

            if (visualState.Storyboard == null)
            {
                taskSource.TrySetResult(false);
                return taskSource.Task;
            }

            EventHandler storyboardCompletedHandler = null;
            storyboardCompletedHandler = (s, e) =>
                {
                    visualState.Storyboard.Completed -= storyboardCompletedHandler;
                    taskSource.TrySetResult(true);
                };

            visualState.Storyboard.Completed += storyboardCompletedHandler;
            VisualStateManager.GoToState(control, state, true);
            return taskSource.Task;
        }
开发者ID:jorik041,项目名称:CrossChat,代码行数:27,代码来源:VisualStateManagerExtensions.cs

示例5: Main

        static void Main(string[] args)
        {
            var tcs = new TaskCompletionSource<int>();
            
            var ct = new CancellationTokenSource(7000);
            ct.Token.Register(() =>
            {
                Console.WriteLine("Cancel");
                tcs.TrySetResult(1);
            }, useSynchronizationContext: false);

            Stopwatch sw = new Stopwatch();
            sw.Restart();
            Console.WriteLine("StartNew...");
            Task.Factory.StartNew(() =>
            {
                Task.Delay(5000).Wait();
                Console.WriteLine("StartNew...Over");
                tcs.TrySetResult(DateTime.Now.Second);

            });
            
            var i = tcs.Task.Result;
            sw.Stop();
            Console.WriteLine("over..." + sw.Elapsed.TotalSeconds);

            Console.ReadLine();
        }
开发者ID:Indifer,项目名称:Test,代码行数:28,代码来源:Program.cs

示例6: GetResponseAsync

		public static Task<WebResponse> GetResponseAsync(this HttpWebRequest request)
		{
			var taskComplete = new TaskCompletionSource<WebResponse>();

			request.AllowReadStreamBuffering = true;
			request.AllowWriteStreamBuffering = true;

			request.BeginGetResponse(asyncResponse =>
			{
				try
				{
					var responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
					var someResponse = responseRequest.EndGetResponse(asyncResponse);

					taskComplete.TrySetResult(someResponse);
				}
				catch (WebException webExc)
				{
					var failedResponse = webExc.Response;
					taskComplete.TrySetResult(failedResponse);
				}
			}, request);

			return taskComplete.Task;
		}
开发者ID:selaromdotnet,项目名称:Coding4FunToolkit,代码行数:25,代码来源:HttpWebRequestExtensions.cs

示例7: GetResponseStreamAsync

        public static Task<HttpWebResponse> GetResponseStreamAsync(this HttpWebRequest context, object state)
        {
            // this will be our sentry that will know when our async operation is completed
            var tcs = new TaskCompletionSource<HttpWebResponse>();

            try
            {
                context.BeginGetResponse((iar) =>
                {
                    try
                    {
                        var result = context.EndGetResponse(iar as IAsyncResult);
                        tcs.TrySetResult(result as HttpWebResponse);
                    }
                    catch (OperationCanceledException ex)
                    {
                        // if the inner operation was canceled, this task is cancelled too
                        tcs.TrySetCanceled();
                    }
                    catch (Exception ex)
                    {
                        // general exception has been set
                        tcs.TrySetException(ex);
                    }
                }, state);
            }
            catch
            {
                tcs.TrySetResult(default(HttpWebResponse));
                // propagate exceptions to the outside
                throw;
            }

            return tcs.Task;
        }
开发者ID:sridhar19091986,项目名称:sharpmapx,代码行数:35,代码来源:HttpExtensions.cs

示例8: ConfirmAsync

		public Task<bool> ConfirmAsync(string message, string title = "", string okButton = "OK", string cancelButton = "Cancel", TimeSpan? duration = null)
		{
			var tcs = new TaskCompletionSource<bool>();

			Application.SynchronizationContext.Post(ignored =>
			{
				if (CurrentActivity == null) return;

				var builder = new AlertDialog.Builder(CurrentActivity)
					.SetMessage(message)
					.SetTitle(title)
					.SetPositiveButton(okButton, delegate
					{
						tcs.TrySetResult(true);
					})
					.SetNegativeButton(cancelButton, delegate
					{
						tcs.TrySetResult(false);
					});

				var dialog = this.CustomizeAndCreate(builder);
				dialog.Show();

				if (duration.HasValue)
					Task.Delay(duration.Value).ContinueWith((delayTask) => Application.SynchronizationContext.Post(ignored2 => dialog.SafeDismiss(), null));
			}, null);

			return tcs.Task;
		}
开发者ID:ExRam,项目名称:MvvmCross-UserInteraction,代码行数:29,代码来源:UserInteraction.cs

示例9: WaitForButtonPressAsync

        internal Task WaitForButtonPressAsync()
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();

            RoutedEventHandler okHandler = null;
            KeyEventHandler okKeyHandler = null;

            KeyEventHandler escapeKeyHandler = null;

            Action cleanUpHandlers = null;

            var cancellationTokenRegistration = DialogSettings.CancellationToken.Register(() =>
            {
                cleanUpHandlers();
                tcs.TrySetResult(null);
            });

            cleanUpHandlers = () => {
                KeyDown -= escapeKeyHandler;

                PART_OkButton.Click -= okHandler;

                PART_OkButton.KeyDown -= okKeyHandler;

                cancellationTokenRegistration.Dispose();
            };

            escapeKeyHandler = (sender, e) =>
            {
                if (e.Key != Key.Escape) return;
                cleanUpHandlers();

                tcs.TrySetResult(null);
            };

            okKeyHandler = (sender, e) =>
            {
                if (e.Key != Key.Enter) return;
                cleanUpHandlers();

                tcs.TrySetResult(null);
            };

            okHandler = (sender, e) =>
            {
                cleanUpHandlers();

                tcs.TrySetResult(null);

                e.Handled = true;
            };

            PART_OkButton.KeyDown += okKeyHandler;

            KeyDown += escapeKeyHandler;

            PART_OkButton.Click += okHandler;

            return tcs.Task;
        }
开发者ID:punker76,项目名称:Popcorn,代码行数:60,代码来源:ExceptionDialog.xaml.cs

示例10: WaitForButtonPressAsync

        internal Task<MessageDialogResult> WaitForButtonPressAsync()
        {
            AffirmativeButton.Focus();

            TaskCompletionSource<MessageDialogResult> tcs = new TaskCompletionSource<MessageDialogResult>();

            RoutedEventHandler negativeHandler = null;
            RoutedEventHandler affirmativeHandler = null;

            negativeHandler = new RoutedEventHandler((sender, e) =>
                {
                    NegativeButton.Click -= negativeHandler;
                    AffirmativeButton.Click -= affirmativeHandler;

                    tcs.TrySetResult(MessageDialogResult.Negative);
                });

            affirmativeHandler = new RoutedEventHandler((sender, e) =>
                {
                    NegativeButton.Click -= negativeHandler;
                    AffirmativeButton.Click -= affirmativeHandler;

                    tcs.TrySetResult(MessageDialogResult.Affirmative);
                });

            NegativeButton.Click += negativeHandler;
            AffirmativeButton.Click += affirmativeHandler;

            return tcs.Task;
        }
开发者ID:jagui,项目名称:MahApps.Metro,代码行数:30,代码来源:MessageDialog.cs

示例11: OnSuccess

        /// <summary>
        /// Callback method once the login method is successfull.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="tcs"></param>
        protected static void OnSuccess(Uri uri, TaskCompletionSource<OAuthResult> tcs)
        {
            var queryParams = uri.Query;
            var parts = queryParams.Split('&');
            var queryMap = parts.Select(t => t.Split('=')).ToDictionary(kv => kv[0], kv => kv[1]);

            string result;
            queryMap.TryGetValue("result", out result);
            if ("success" == result)
            {
                string sessionToken;
                string authRes;
                queryMap.TryGetValue("fh_auth_session", out sessionToken);
                queryMap.TryGetValue("authResponse", out authRes);
                var oauthResult = new OAuthResult(OAuthResult.ResultCode.Ok, sessionToken,
                    Uri.UnescapeDataString(authRes));
                tcs.TrySetResult(oauthResult);
            }
            else
            {
                string errorMessage;
                queryMap.TryGetValue("message", out errorMessage);
                var oauthResult = new OAuthResult(OAuthResult.ResultCode.Failed, new Exception(errorMessage));
                tcs.TrySetResult(oauthResult);
            }
        }
开发者ID:secondsun,项目名称:fh-dotnet-sdk,代码行数:31,代码来源:IOAuthClientHandlerService.cs

示例12: WaitForChangeAsync

        public async Task<string> WaitForChangeAsync(CancellationToken cancellationToken)
        {
            _watchedFiles = GetProjectFilesClosure(_rootProject);

            foreach (var file in _watchedFiles)
            {
                _fileWatcher.WatchDirectory(Path.GetDirectoryName(file));
            }

            var tcs = new TaskCompletionSource<string>();
            cancellationToken.Register(() => tcs.TrySetResult(null));

            Action<string> callback = path =>
            {
                // If perf becomes a problem, this could be a good starting point
                // because it reparses the project on every change
                // Maybe it could time-buffer the changes in case there are a lot
                // of files changed at the same time
                if (IsFileInTheWatchedSet(path))
                {
                    tcs.TrySetResult(path);
                }
            };

            _fileWatcher.OnFileChange += callback;
            var changedFile = await tcs.Task;
            _fileWatcher.OnFileChange -= callback;

            return changedFile;
        }
开发者ID:aspnet,项目名称:dotnet-watch,代码行数:30,代码来源:ProjectWatcher.cs

示例13: GetConfigurationAsync

		public Task<ConfigurationResponse> GetConfigurationAsync () {
			var tcs = new TaskCompletionSource<ConfigurationResponse> ();
			Task.Factory.StartNew (async () => {
				var urlString = String.Format (SharedConstants.GetConfigurationUriFormatString, SharedConstants.ApiKey);
				var cacheKey = this.getCacheKey (urlString);
				if (this.configuration != null) {
					tcs.TrySetResult (this.configuration);
				} else {
					if (cache.ContainsKey(cacheKey)) {
						var response = cache.Get<ConfigurationResponse>(cacheKey);
						this.configuration = response;
						tcs.TrySetResult (this.configuration);
					} else {
						var client = this.httpClientFactory.Create ();
						var response = await client.GetAsync (urlString);
						var json = await response.Content.ReadAsStringAsync ();
						var result = JsonConvert.DeserializeObject<ConfigurationResponse> (json);
						this.configuration = result;
						cache.Set<ConfigurationResponse> (cacheKey, this.configuration);
						tcs.TrySetResult (this.configuration);
					}
				}
			});
			return tcs.Task;
		}
开发者ID:Robert-Altland,项目名称:MovieExplorer,代码行数:25,代码来源:Data.cs

示例14: GetAllAsync

        public Task<Contact[]> GetAllAsync()
        {
            var taskCompletionSource = new TaskCompletionSource<Contact[]>();

            NSError err;
            var ab = ABAddressBook.Create(out err);
            if (err != null)
            {
                // process error
                return Task.FromResult(new Contact[0]);
            }
            // if the app was not authorized then we need to ask permission
            if (ABAddressBook.GetAuthorizationStatus() != ABAuthorizationStatus.Authorized)
            {
                ab.RequestAccess(delegate(bool granted, NSError error)
                {
                    if (error != null)
                    {
                        taskCompletionSource.TrySetResult(new Contact[0]);
                    }
                    else if (granted)
                    {
                        Task.Run(() => taskCompletionSource.TrySetResult(GetContacts(ab)));
                    }
                });
            }
            else
            {
                Task.Run(() => taskCompletionSource.TrySetResult(GetContacts(ab)));
            } 

            return taskCompletionSource.Task;
        }
开发者ID:EgorBo,项目名称:CrossChat-Xamarin.Forms,代码行数:33,代码来源:ContactsRepository.cs

示例15: ShowFolderDialogAsync

        public Task<string> ShowFolderDialogAsync(OpenFolderDialog dialog, IWindowImpl parent)
        {
            var tcs = new TaskCompletionSource<string>();
            var dlg = new global::Gtk.FileChooserDialog(dialog.Title, ((WindowImpl)parent),
                FileChooserAction.SelectFolder,
                "Cancel", ResponseType.Cancel,
                "Select Folder", ResponseType.Accept)
            {

            };

            dlg.Modal = true;

            dlg.Response += (_, args) =>
            {
                if (args.ResponseId == ResponseType.Accept)
                    tcs.TrySetResult(dlg.Filename);

                dlg.Hide();
                dlg.Dispose();
            };

            dlg.Close += delegate
            {
                tcs.TrySetResult(null);
                dlg.Dispose();
            };
            dlg.Show();
            return tcs.Task;
        }
开发者ID:KvanTTT,项目名称:Perspex,代码行数:30,代码来源:SystemDialogImpl.cs


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