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


C# TaskCompletionSource.SetCanceled方法代码示例

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


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

示例1: ReturnFile

 public Task ReturnFile(IDictionary<string, object> env)
 {
     var tcs = new TaskCompletionSource<int>();
     if (env.GetPath().ToLower().Equals("/index.html", StringComparison.CurrentCultureIgnoreCase))
     {
         try
         {
             env["owin.ResponseHeaders"] = new Dictionary<string, string[]>
                                               {
                                                   {
                                                       "Content-Type",
                                                       new[] {"text/html"}
                                                   }
                                               };
             HandleRequest(env);
             env["owin.ResponseStatusCode"] = 200;
             tcs.SetResult(0);
         }
         catch (Exception ex)
         {
             Trace.TraceError(ex.Message);
             tcs.SetCanceled();
         }
     }
     else
     {
         tcs.SetCanceled();
     }
     return tcs.Task;
 }
开发者ID:nordbergm,项目名称:Fix,代码行数:30,代码来源:FileReturner.cs

示例2: GetSongs

        public Task<IEnumerable<Song>> GetSongs(string query, CancellationToken cancellationToken)
        {
            var result = MemoryCache.Default.Get(query) as IEnumerable<Song>;

            if (result != null)
            {
                return Task.Factory.StartNew(() => result);
            }

            var tcs = new TaskCompletionSource<IEnumerable<Song>>();

            _provider
                .GetSongs(query, cancellationToken)
                .ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        tcs.SetException(t.Exception);
                    }
                    else if (t.IsCanceled)
                    {
                        tcs.SetCanceled();
                    }
                    else
                    {
                        MemoryCache.Default.Set(query, t.Result, new CacheItemPolicy { SlidingExpiration = SlidingExpiration });
                        tcs.SetResult(t.Result);
                    }
                });

            return tcs.Task;
        }
开发者ID:torshy,项目名称:TRock.Music,代码行数:32,代码来源:CachedSongProvider.cs

示例3: Should_call_onBulkheadRejected_with_passed_context

        public void Should_call_onBulkheadRejected_with_passed_context()
        {
            string executionKey = Guid.NewGuid().ToString();
            Context contextPassedToExecute = new Context(executionKey);

            Context contextPassedToOnRejected = null;
            Func<Context, Task> onRejectedAsync = async ctx => { contextPassedToOnRejected = ctx; await TaskHelper.EmptyTask.ConfigureAwait(false); };

            BulkheadPolicy<int> bulkhead = Policy.BulkheadAsync<int>(1, onRejectedAsync);

            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            using (CancellationTokenSource cancellationSource = new CancellationTokenSource())
            {
                Task.Run(() => {
                    bulkhead.ExecuteAsync(async () =>
                    {
                        await tcs.Task.ConfigureAwait(false);
                        return 0;
                    });
                });

                Within(shimTimeSpan, () => bulkhead.BulkheadAvailableCount.Should().Be(0)); // Time for the other thread to kick up and take the bulkhead.

                bulkhead.Awaiting(async b => await b.ExecuteAsync(() => Task.FromResult(1), contextPassedToExecute)).ShouldThrow<BulkheadRejectedException>();

                cancellationSource.Cancel();
                tcs.SetCanceled();
            }

            contextPassedToOnRejected.Should().NotBeNull();
            contextPassedToOnRejected.ExecutionKey.Should().Be(executionKey);
            contextPassedToOnRejected.Should().BeSameAs(contextPassedToExecute);
        }
开发者ID:App-vNext,项目名称:Polly,代码行数:33,代码来源:BulkheadTResultAsyncSpecs.cs

示例4: GetStreamAsync

		public Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken)
		{
			var tcs = new TaskCompletionSource<Stream>();

			try
			{
				HttpWebRequest request = WebRequest.CreateHttp(uri);
				request.AllowReadStreamBuffering = true;
				request.BeginGetResponse(ar =>
				{
					if (cancellationToken.IsCancellationRequested)
					{
						tcs.SetCanceled();
						return;
					}

					try
					{
						Stream stream = request.EndGetResponse(ar).GetResponseStream();
						tcs.TrySetResult(stream);
					}
					catch (Exception ex)
					{
						tcs.TrySetException(ex);
					}
				}, null);
			}
			catch (Exception ex)
			{
				tcs.TrySetException(ex);
			}

			return tcs.Task;
		}
开发者ID:Costo,项目名称:Xamarin.Forms,代码行数:34,代码来源:WP8PlatformServices.cs

示例5: GetAsset

        Task<ALAsset> GetAsset (AssetDescription description, CancellationToken token)
        {
            var tcs = new TaskCompletionSource<ALAsset> ();

            Task.Factory.StartNew (() => {
                if (token.IsCancellationRequested) {
                    tcs.SetCanceled ();
                    return;
                }

                _library.Value.AssetForUrl (new NSUrl (description.AssetUrl), (asset) => {
                    if (asset == null) {
                        tcs.SetException (new Exception ("No asset found for url"));
                        return;
                    }

                    if (asset.DefaultRepresentation == null) {
                        tcs.SetException (new Exception ("No representation found for the asset"));
                        return;
                    }

                    tcs.SetResult (asset);
                }, error => {
                    tcs.SetException (new Exception (error.ToString ()));
                });
            }, token).RouteExceptions (tcs);

            return tcs.Task;
        }
开发者ID:stampsy,项目名称:Stampsy.ImageSource,代码行数:29,代码来源:AssetSource.cs

示例6: SaveChanges

        /// <summary>
        /// If AutoSaveChanges is set this method will auto commit changes
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected virtual Task<int> SaveChanges(CancellationToken cancellationToken)
        {
            var source = new TaskCompletionSource<int>();
            if (AutoSaveChanges) {
                var registration = new CancellationTokenRegistration();
                if (cancellationToken.CanBeCanceled) {
                    if (cancellationToken.IsCancellationRequested) {
                        source.SetCanceled();
                        return source.Task;
                    }
                    registration = cancellationToken.Register(CancelIgnoreFailure);
                }

                try
                {
                    return _uow.SaveChangesAsync(cancellationToken);
                }
                catch (Exception e)
                {
                    source.SetException(e);
                }
                finally
                {
                    registration.Dispose();
                }
            }
            return source.Task;
        }
开发者ID:rubenknuijver,项目名称:Jigsaw,代码行数:33,代码来源:DataStore.cs

示例7: OnUIThreadAsync

        /// <summary>
        ///   Executes the action on the UI thread asynchronously.
        /// </summary>
        /// <param name = "action">The action to execute.</param>
        public Task OnUIThreadAsync(Action action)
        {
            var completionSource = new TaskCompletionSource<bool>();

            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {

                try
                {
                    action();

                    completionSource.SetResult(true);

                }
                catch (TaskCanceledException)
                {
                    completionSource.SetCanceled();
                }
                catch (Exception ex)
                {
                    completionSource.SetException(ex);
                }

            });

            return completionSource.Task;
        }
开发者ID:mvermef,项目名称:Caliburn.Micro,代码行数:31,代码来源:iOSPlatformProvider.cs

示例8: ConfirmationAsync

		public static Task<bool> ConfirmationAsync(string title, string question)
		{
			var dataContext = new ConfirmModel
			{
				Title = title,
				Question = question
			};
			var inputWindow = new ConfirmWindow
			{
				DataContext = dataContext
			};

			var tcs = new TaskCompletionSource<bool>();

			inputWindow.Closed += (sender, args) =>
			{
				if (inputWindow.DialogResult != null)
					tcs.SetResult(inputWindow.DialogResult.Value);
				else
					tcs.SetCanceled();
			};

			inputWindow.Show();

			return tcs.Task;
		}
开发者ID:neiz,项目名称:ravendb,代码行数:26,代码来源:AskUser.cs

示例9: WriteResponse

 private static Task WriteResponse(OwinContext context, IDictionary<string, object> env)
 {
     var tcs = new TaskCompletionSource<int>();
     var cancellationToken = (CancellationToken) env[OwinKeys.CallCancelled];
     if (cancellationToken.IsCancellationRequested)
     {
         tcs.SetCanceled();
     }
     else
     {
         try
         {
             env[OwinKeys.StatusCode] = context.Response.Status.Code;
             env[OwinKeys.ReasonPhrase] = context.Response.Status.Description;
             env[OwinKeys.ResponseHeaders] = context.Response.Headers;
             if (context.Response.WriteFunction != null)
             {
                 return context.Response.WriteFunction((Stream) env[OwinKeys.ResponseBody]);
             }
             tcs.SetResult(0);
         }
         catch (Exception ex)
         {
             tcs.SetException(ex);
         }
     }
     return tcs.Task;
 }
开发者ID:nordbergm,项目名称:Simple.Web,代码行数:28,代码来源:Application.cs

示例10: Automatically_Validate_Address

        public Task<Address_Validated> Automatically_Validate_Address(string textAddress)
        {
            var tcs = new TaskCompletionSource<Address_Validated>();

            var geocoding = maps.ServiceHelper.GetGeocodeService();
            geocoding.GeocodeCompleted += (sender, e) =>
            {
                //if (e.Error != null)
                //    tcs.SetCanceled();

                if (e.Error == null && e.Result.Results.GroupBy(f=> f.Address.FormattedAddress).Count() == 1)
                {
                    var validated = new Address_Validated(e.Result.Results.First(), null);
                    //MessageBus.Current.SendMessage(new Address_Validated(e.Result.Results.First(), search_Address));
                    tcs.TrySetResult(validated);
                }
                else
                {
                    tcs.SetCanceled();
                    //MessageBus.Current.SendMessage(search_Address.To_Manual());
                    //var task = Manually_Validate_Address(textAddress);
                    //task.Wait();
                }
            };

            geocoding.GeocodeAsync(new maps.GeocodeService.GeocodeRequest
            {
                Credentials = new Microsoft.Maps.MapControl.Credentials() { Token = maps.ServiceHelper.GeocodeServiceCredentials },
                Culture = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(),
                Query = textAddress
            });

            return tcs.Task;
        }
开发者ID:valeriob,项目名称:Routing,代码行数:34,代码来源:Address_Validation_Helper.cs

示例11: Should_call_on_error

        public async Task Should_call_on_error(TransportTransactionMode transactionMode)
        {
            var onErrorCalled = new TaskCompletionSource<ErrorContext>();

            OnTestTimeout(() => onErrorCalled.SetCanceled());

            await StartPump(context =>
            {
                throw new Exception("Simulated exception");
            },
                context =>
                {
                    onErrorCalled.SetResult(context);

                    return Task.FromResult(ErrorHandleResult.Handled);
                }, transactionMode);

            await SendMessage(InputQueueName, new Dictionary<string, string> { { "MyHeader", "MyValue" } });

            var errorContext = await onErrorCalled.Task;

            Assert.AreEqual(errorContext.Exception.Message, "Simulated exception", "Should preserve the exception");
            Assert.AreEqual(1, errorContext.ImmediateProcessingFailures, "Should track the number of delivery attempts");
            Assert.AreEqual("MyValue", errorContext.Message.Headers["MyHeader"], "Should pass the message headers");
        }
开发者ID:Particular,项目名称:NServiceBus,代码行数:25,代码来源:When_on_message_throws.cs

示例12: Should_call_onBulkheadRejected_with_passed_context

        public void Should_call_onBulkheadRejected_with_passed_context()
        {
            string executionKey = Guid.NewGuid().ToString();
            Context contextPassedToExecute = new Context(executionKey);

            Context contextPassedToOnRejected = null;
            Action<Context> onRejected = ctx => { contextPassedToOnRejected = ctx; };

            BulkheadPolicy<int> bulkhead = Policy.Bulkhead<int>(1, onRejected);

            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            using (CancellationTokenSource cancellationSource = new CancellationTokenSource())
            {
                Task.Run(() => {
                    bulkhead.Execute(() =>
                    {
                        tcs.Task.Wait();
                        return 0;
                    });
                });

                Within(shimTimeSpan, () => bulkhead.BulkheadAvailableCount.Should().Be(0)); // Time for the other thread to kick up and take the bulkhead.

                bulkhead.Invoking(b => b.Execute(() => 1, contextPassedToExecute)).ShouldThrow<BulkheadRejectedException>();

                cancellationSource.Cancel();
                tcs.SetCanceled();
            }

            contextPassedToOnRejected.Should().NotBeNull();
            contextPassedToOnRejected.ExecutionKey.Should().Be(executionKey);
            contextPassedToOnRejected.Should().BeSameAs(contextPassedToExecute);
        }
开发者ID:App-vNext,项目名称:Polly,代码行数:33,代码来源:BulkheadTResultSpecs.cs

示例13: DownloadDataTaskAsync

        public static Task<Byte[]> DownloadDataTaskAsync(this WebClient client, Uri address)
        {
            var completerionSource = new TaskCompletionSource<byte[]>();
            var token = new object();

            OpenReadCompletedEventHandler handler = null;
            handler = (sender, args) =>
            {
                if (args.UserState != token)
                {
                    return;
                }

                if (args.Error != null)
                {
                    completerionSource.SetException(args.Error);
                }
                else if (args.Cancelled)
                {
                    completerionSource.SetCanceled();
                }
                else
                {
                    completerionSource.SetResult(args.Result.ToArray());
                }

                client.OpenReadCompleted -= handler;
            };

            client.OpenReadCompleted += handler;
            client.OpenReadAsync(address, token);

            return completerionSource.Task;
        }
开发者ID:mdabbagh88,项目名称:UniversalImageLoader,代码行数:34,代码来源:WebClientExtensions.cs

示例14: AlertUser

        public static Task AlertUser(string title, string message)
        {
            var dataContext = new ConfirmModel
			{
				Title = title,
				Message = message,
                AllowCancel = false,
			};
			var inputWindow = new ConfirmWindow()
			{
				DataContext = dataContext
			};

			var tcs = new TaskCompletionSource<bool>();

			inputWindow.Closed += (sender, args) =>
			{
				if (inputWindow.DialogResult == true)
					tcs.SetResult(true);
				else
					tcs.SetCanceled();
			};

			inputWindow.Show();

			return tcs.Task;
        }
开发者ID:hibernating-rhinos,项目名称:RavenFS,代码行数:27,代码来源:AskUser.cs

示例15: QuestionAsync

		public static Task<string> QuestionAsync(string title, string question, Func<string,string> validator = null, string defaultAnswer = "")
		{
			var dataContext = new InputModel
			{
				Title = title,
				Message = question,
                ValidationCallback = validator,
			};

            dataContext.SetDefaultAnswer(defaultAnswer);

			var inputWindow = new InputWindow
			{
				DataContext = dataContext
			};

			var tcs = new TaskCompletionSource<string>();

			inputWindow.Closed += (sender, args) =>
			{
				if (inputWindow.DialogResult == true)
					tcs.SetResult(dataContext.Answer);
				else
					tcs.SetCanceled();
			};

			inputWindow.Show();

			return tcs.Task;
		}
开发者ID:hibernating-rhinos,项目名称:RavenFS,代码行数:30,代码来源:AskUser.cs


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