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


C# CancellationToken类代码示例

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


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

示例1: SendAsync

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Method == HttpMethod.Get && request.RequestUri.Segments.Last() == "authtoken")
        {
            string querystring = request.RequestUri.Query.Substring(1);
            string[] queryParams = querystring.Split(new[] { '&' });

            var queryStringParams = request.RequestUri.ParseQueryString();
            if (queryStringParams.Count > 0)
            {
                string code = queryParams.Where(p => p.StartsWith("code")).First().Split(new[] { '=' })[1];

                return Task.Factory.StartNew(
                    () =>
                    {
                        string accessToken = this.GetFacebookAccessToken(code, request);
                        string username = GetFacebookUsername(accessToken);

                        var ticket = new FormsAuthenticationTicket(username, false, 60);
                        string s = FormsAuthentication.Encrypt(ticket);

                        var response = new HttpResponseMessage();
                        response.Headers.Add("Set-Cookie", string.Format("ticket={0}; path=/", s));

                        var responseContentBuilder = new StringBuilder();
                        responseContentBuilder.AppendLine("<html>");
                        responseContentBuilder.AppendLine("   <head>");
                        responseContentBuilder.AppendLine("      <title>Login Callback</title>");
                        responseContentBuilder.AppendLine("   </head>");
                        responseContentBuilder.AppendLine("   <body>");
                        responseContentBuilder.AppendLine("      <script type=\"text/javascript\">");
                        responseContentBuilder.AppendLine(
                            "         if(window.opener){");

                        if (queryStringParams["callback"] != null)
                        {
                            responseContentBuilder.AppendLine(queryStringParams["callback"] + "();");
                        }

                        responseContentBuilder.AppendLine("            window.close()';");
                        responseContentBuilder.AppendLine("         }");
                        responseContentBuilder.AppendLine("      </script>");
                        responseContentBuilder.AppendLine("   </body>");
                        responseContentBuilder.AppendLine("</html>");

                        response.Content = new StringContent(responseContentBuilder.ToString());
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                        response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };

                        return response;
                    });
            }

            return Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));
        }

        return base.SendAsync(request, cancellationToken);
    }
开发者ID:Tinytoot,项目名称:TeamThing,代码行数:59,代码来源:OAuthMessageHandler.cs

示例2: SendAsync

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var authHeader = request.Headers.Authorization;

        if (authHeader == null)
            return base.SendAsync(request, cancellationToken);

        if (authHeader.Scheme != "Basic")
            return base.SendAsync(request, cancellationToken);

        if (String.IsNullOrEmpty(authHeader.Parameter))
            return base.SendAsync(request, cancellationToken);

        var encodedUserPass = authHeader.Parameter.Trim();
        var userPass = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass));
        var parts = userPass.Split(":".ToCharArray());
        var email = parts[0];
        var password = parts[1];
        var mem = new UserMembershipProvider();
        if (!mem.ValidateUserEncoded(email, password))
            return base.SendAsync(request, cancellationToken);

        var i = new RadarIdentity(email, "Basic");
        //var identity = new GenericIdentity(username, "Basic");

        //string[] roles = RadarRoleProvider.GetRolesForUser(email);
        var p = new RadarPrincipal(i);
        //var principal = new GenericPrincipal(i, roles);
        Thread.CurrentPrincipal = p;

        if (HttpContext.Current != null)
            HttpContext.Current.User = p;

        return base.SendAsync(request, cancellationToken);
    }
开发者ID:tep-pl,项目名称:Radar,代码行数:35,代码来源:BasicAuthenticationMessageHandler.cs

示例3: ExecuteAsync

 public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
 {
     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
     response.Content = new StringContent(Content);
     response.RequestMessage = Request;
     return Task.FromResult(response);
 }
开发者ID:chimpinano,项目名称:generator-webapi-owin-jwt-aspnet-identity,代码行数:7,代码来源:_apiglobalexceptionhandler.cs

示例4: SendAsync

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // if request is local, just serve it without https
        object httpContextBaseObject;
        if (request.Properties.TryGetValue("MS_HttpContext", out httpContextBaseObject))
        {
            var httpContextBase = httpContextBaseObject as HttpContextBase;

            if (httpContextBase != null && httpContextBase.Request.IsLocal)
            {
                return base.SendAsync(request, cancellationToken);
            }
        }

        // if request is remote, enforce https
        if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            return Task<HttpResponseMessage>.Factory.StartNew(
                () =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                    {
                        Content = new StringContent("HTTPS Required")
                    };

                    return response;
                });
        }

        return base.SendAsync(request, cancellationToken);
    }
开发者ID:jmstefans,项目名称:FlavorOfTheMonth,代码行数:31,代码来源:EnforceHttpsHandler.cs

示例5: Iterate

 /// <summary>Asynchronously iterates through an enumerable of tasks.</summary>
 /// <param name="factory">The target factory.</param>
 /// <param name="source">The enumerable containing the tasks to be iterated through.</param>
 /// <param name="cancellationToken">The cancellation token used to cancel the iteration.</param>
 /// <param name="creationOptions">Options that control the task's behavior.</param>
 /// <param name="scheduler">The scheduler to which tasks will be scheduled.</param>
 /// <returns>A Task that represents the complete asynchronous operation.</returns>
 public static Task Iterate(
     this TaskFactory factory,
     IEnumerable<object> source,
     CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
 {
     return Iterate(factory, source, null, cancellationToken, creationOptions, scheduler);
 }
开发者ID:Farfeght,项目名称:parallel-extensions-extras,代码行数:14,代码来源:TaskFactoryExtensions_Iterate.cs

示例6: Authenticate

        /// <summary>
        /// Takes an OAuth code and turns it into an API token.
        /// </summary>
        /// <param name="code">A code returned from the OAuth page (https://quizlet.com/authorize/)</param>
        /// <param name="success">A delegate to be called when the authentication succeeds.</param>
        /// <param name="failure">What to do when the authentication fails.</param>
        /// <param name="token">A CancellationToken, which is currently useless.</param>
        public void Authenticate(string code, Action success, Action<Exception> failure, CancellationToken token)
        {
            var fields = "grant_type=authorization_code&code=" + code + "&redirect_uri=https://q.asztal.net/";

            var req = new HttpsRequest("POST", "/oauth/token");
            req.BasicAuthorization(ClientID, SecretKey);

            req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            req.PostData = Encoding.UTF8.GetBytes(fields);

            FetchJSON(req,
            json => {
                try {
                    if (json is JsonDictionary) {
                        var ctx = new JsonContext();

                        var accessToken = ctx.FromJson<string>((json as JsonDictionary).Items["access_token"]);
                        var userName = ctx.FromJson<string>((json as JsonDictionary).Items["user_id"]);
                        var tokenExpiry = DateTime.Now.AddSeconds(ctx.FromJson<double>((json as JsonDictionary).Items["expires_in"]));
                        Credentials = new Credentials(accessToken, userName, tokenExpiry);

                        success();
                    } else {
                        failure(new FormatException("Quizlet server returned an invalid response."));
                    }
                } catch (KeyNotFoundException) {
                    failure(new FormatException("Quizlet server returned an invalid response."));
                } catch (JsonConvertException) {
                    failure(new FormatException("Quizlet server returned an invalid response."));
                }
            },
            failure,
            token);
        }
开发者ID:aata,项目名称:flashcards-wp7,代码行数:41,代码来源:QuizletAPI.cs

示例7: ExecuteAuthorizationFilterAsync

            //// this is Castle.Core.Logging.ILogger, not log4net.Core.ILogger
            //public ILogger Logger { get; set; }
            /// <summary>
            /// Executes the authorization filter.
            /// </summary>
            /// <param name="actionContext">The action context.</param>
            /// <param name="cancellationToken">The cancellation token associated with the filter.</param>
            /// <param name="continuation">The continuation.</param>
            /// <returns>
            /// The authorization filter to synchronize.
            /// </returns>
            public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
            {
                HttpRequestMessage request = actionContext.Request;

                try
                {
                    if (IsAjaxRequest(request))
                    {
                        ValidateRequestHeader(request);
                    }
                    else
                    {
                        AntiForgery.Validate();
                    }
                }
                catch (Exception)
                {
                    //LogManager.GetCurrentClassLogger().Warn("Anti-XSRF Validation Failed", ex);

                    actionContext.Response = new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Forbidden,
                        RequestMessage = actionContext.ControllerContext.Request
                    };
                    return FromResult(actionContext.Response);
                }
                return continuation();
            }
开发者ID:jioe,项目名称:appverse-net,代码行数:39,代码来源:ValidateHttpAntiForgeryToken.cs

示例8: Sum

 private static Int32 Sum(CancellationToken cancelToken, Int32 n) {
     Int32 sum = 0;
     for (; n > 0; n--){
         cancelToken.ThrowIfCancellationRequested();
         checked{ sum += n; }            
     }
     return sum;
 }
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:8,代码来源:TaskFactory.cs

示例9: SendAsync

 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     request.Headers.Add("Cookie", this.cookie);
     request.Headers.Add("X-Unity-Version", GameInfo.instance.UV);
     request.Headers.Add("charset", "UTF-8");
     request.Headers.Add("UserAgent", GameInfo.instance.UA);
     request.Headers.Add("Connection", "Keep-Alive");
     return base.SendAsync(request, cancellationToken);
 }
开发者ID:lavender1213,项目名称:ShipGirlBot,代码行数:9,代码来源:ShipHttpClientHandler.cs

示例10: DownloadAndCountBytesAsync

 // http://blogs.msdn.com/b/lucian/archive/2012/12/08/await-httpclient-getstringasync-and-cancellation.aspx
 public static async Task<int> DownloadAndCountBytesAsync(string url, CancellationToken token = new CancellationToken())
 {
     await Task.Delay(TimeSpan.FromSeconds(3), token).ConfigureAwait(false);
     var client = new HttpClient();
     using (var response = await client.GetAsync(url, token).ConfigureAwait(false))
     {
         var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
         return data.Length;
     }
 }
开发者ID:timotei,项目名称:AsyncCommands,代码行数:11,代码来源:Service.cs

示例11: CancellationGuard

        /// <summary>
        /// Registers a callback for the <paramref name="cancellationToken"/> that blocks calls to <see cref="CancellationTokenSource.Cancel()"/> until <see cref="Dispose"/> has been called.
        /// </summary>
        /// <param name="cancellationToken">Used to signal cancellation requests.</param>
        public CancellationGuard(CancellationToken cancellationToken)
        {
            _registration = cancellationToken.Register(
#if NET40 || NET45
                _tcs.Task.Wait
#else
                () => _event.WaitOne()
#endif
            );
        }
开发者ID:nano-byte,项目名称:common,代码行数:14,代码来源:CancellationGuard.cs

示例12: EnsureOperationCanceledExceptionThrown

        private static void EnsureOperationCanceledExceptionThrown(Action action, CancellationToken token, string message)
        {
            OperationCanceledException operationCanceledEx =
                Assert.Throws<OperationCanceledException>(action);

            if (operationCanceledEx.CancellationToken != token)
            {
                Assert.True(false, string.Format("ManualResetEventCancellationTests: Failed.  " + message));
            }
        }
开发者ID:JerryForNet,项目名称:corefx,代码行数:10,代码来源:ManualResetEventSlimCancellationTests.cs

示例13: SendAsync

        public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
        {
            var mockResponseMessage = new HttpResponseMessage()
            {
                //Mock content contains json of two face results
                Content = new StringContent("[\n {\n \"faceRectangle\": {\n \"left\": 68,\n \"top\": 97,\n \"width\": 64,\n \"height\": 97\n },\n \"scores\": {\n \"anger\": 0.00300731952,\n \"contempt\": 5.14648448E-08,\n \"disgust\": 9.180124E-06,\n \"fear\": 0.0001912825,\n \"happiness\": 0.9875571,\n \"neutral\": 0.0009861537,\n \"sadness\": 1.889955E-05,\n \"surprise\": 0.008229999\n }\n },\n{\n \"faceRectangle\": {\n \"left\": 68,\n \"top\": 97,\n \"width\": 64,\n \"height\": 97\n },\n \"scores\": {\n \"anger\": 0.00300731952,\n \"contempt\": 5.14648448E-08,\n \"disgust\": 9.180124E-06,\n \"fear\": 0.0001912825,\n \"happiness\": 0.9875571,\n \"neutral\": 0.0009861537,\n \"sadness\": 1.889955E-05,\n \"surprise\": 0.008229999\n }\n }\n]"),
                StatusCode = HttpStatusCode.OK
            };

            return Task.FromResult(mockResponseMessage);
        }
开发者ID:gitter-badger,项目名称:Emotion-API,代码行数:11,代码来源:EmotionAPIClientFixture.cs

示例14: DownloadAsStringAsync

	/// <summary>
	/// Downloads a file as a string.
	/// </summary>
	/// <param name="address">File URL</param>
	/// <param name="cancellationToken">Optional cancellation token</param>
	public static Task<string> DownloadAsStringAsync(string address, CancellationToken cancellationToken = new CancellationToken())
	{
		return Task.Factory.StartNew(
			delegate
			{
				using (var webClient = new WebClient())
				{
					return webClient.DownloadString(address);
				}
			}, cancellationToken);
	}
开发者ID:Awesome-MQP,项目名称:Storybook,代码行数:16,代码来源:AsyncTools.cs

示例15: MultiplyParallel

 public static void MultiplyParallel(CancellationToken cancellationToken, Matrix src1, Matrix src2, Matrix dst)
 {
     if (src1._size != src2._size || src1._size != dst._size) throw new ArgumentOutOfRangeException("src1");
     int N = src1._size;
     matrix_mult_parallel(
         cancellationToken,
         N, N, N,
         src1._dataPtr, 0, 0, N,
         src2._dataPtr, 0, 0, N,
         dst._dataPtr, 0, 0, N);
 }
开发者ID:Farouq,项目名称:semclone,代码行数:11,代码来源:Matrix.cs


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