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


C# CancellationTokenSource.TimeoutAfter方法代码示例

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


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

示例1: StreamToClient

        private void StreamToClient(Stream stream, int pageSize, Etag etag, OrderedPartCollection<AbstractFileReadTrigger> readTriggers)
        {
            using (var cts = new CancellationTokenSource())
            using (var timeout = cts.TimeoutAfter(FileSystemsLandlord.SystemConfiguration.DatabaseOperationTimeout))
            using (var writer = new JsonTextWriter(new StreamWriter(stream)))
            {
                writer.WriteStartObject();
                writer.WritePropertyName("Results");
                writer.WriteStartArray();

                Storage.Batch(accessor =>
                {
                    var files = accessor.GetFilesAfter(etag, pageSize);
                    foreach (var file in files)
                    {
                        if (readTriggers.CanReadFile(file.FullPath, file.Metadata, ReadOperation.Load) == false)
                            continue;

                        timeout.Delay();
                        var doc = RavenJObject.FromObject(file);
                        doc.WriteTo(writer);

                        writer.WriteRaw(Environment.NewLine);
                    }
                });

                writer.WriteEndArray();
                writer.WriteEndObject();
                writer.Flush();
            }
        }
开发者ID:hero106wen,项目名称:ravendb,代码行数:31,代码来源:FilesStreamsController.cs

示例2: StreamToClient

        private void StreamToClient(Stream stream, int pageSize, Etag etag)
        {
            using (var cts = new CancellationTokenSource())
			using (var timeout = cts.TimeoutAfter(FileSystemsLandlord.SystemConfiguration.DatabaseOperationTimeout))
			using (var writer = new JsonTextWriter(new StreamWriter(stream)))
			{
			    writer.WriteStartObject();
			    writer.WritePropertyName("Results");
			    writer.WriteStartArray();

                Storage.Batch(accessor =>
                {
                    var files = accessor.GetFilesAfter(etag, pageSize);
                    foreach (var file in files)
                    {
                        timeout.Delay();
                        var doc = RavenJObject.FromObject(file);
                        doc.WriteTo(writer);

                        writer.WriteRaw(Environment.NewLine);
                    }
                });

                writer.WriteEndArray();
                writer.WriteEndObject();
                writer.Flush();
			}
        }
开发者ID:bbqchickenrobot,项目名称:ravendb,代码行数:28,代码来源:FilesStreamsController.cs

示例3: Respond

		public override void Respond(IHttpContext context)
		{
			using (var cts = new CancellationTokenSource())
			{
				var timeout = cts.TimeoutAfter(Settings.DatbaseOperationTimeout);
				var databaseBulkOperations = new DatabaseBulkOperations(Database, GetRequestTransaction(context), cts.Token, timeout);
				switch (context.Request.HttpMethod)
				{
					case "POST":
						Batch(context);
						break;
					case "DELETE":
						OnBulkOperation(context, databaseBulkOperations.DeleteByIndex);
						break;
					case "PATCH":
						var patchRequestJson = context.ReadJsonArray();
						var patchRequests = patchRequestJson.Cast<RavenJObject>().Select(PatchRequest.FromJson).ToArray();
						OnBulkOperation(context, (index, query, allowStale) =>
							databaseBulkOperations.UpdateByIndex(index, query, patchRequests, allowStale));
						break;
					case "EVAL":
						var advPatchRequestJson = context.ReadJsonObject<RavenJObject>();
						var advPatch = ScriptedPatchRequest.FromJson(advPatchRequestJson);
						OnBulkOperation(context, (index, query, allowStale) =>
							databaseBulkOperations.UpdateByIndex(index, query, advPatch, allowStale));
						break;
				}
			}
		}
开发者ID:925coder,项目名称:ravendb,代码行数:29,代码来源:DocumentBatch.cs

示例4: BulkPost

		public async Task<HttpResponseMessage> BulkPost()
		{
		    using (var cts = new CancellationTokenSource())
            using (cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
            {
                var jsonCommandArray = await ReadJsonArrayAsync();

				cts.Token.ThrowIfCancellationRequested();

                var transactionInformation = GetRequestTransaction();
                var commands =
                    (from RavenJObject jsonCommand in jsonCommandArray select CommandDataFactory.CreateCommand(jsonCommand, transactionInformation)).ToArray();

                Log.Debug(
                    () =>
                    {
                        if (commands.Length > 15) // this is probably an import method, we will input minimal information, to avoid filling up the log
                        {
                            return "\tExecuted "
                                   + string.Join(
                                       ", ", commands.GroupBy(x => x.Method).Select(x => string.Format("{0:#,#;;0} {1} operations", x.Count(), x.Key)));
                        }

                        var sb = new StringBuilder();
                        foreach (var commandData in commands)
                        {
                            sb.AppendFormat("\t{0} {1}{2}", commandData.Method, commandData.Key, Environment.NewLine);
                        }
                        return sb.ToString();
                    });

                var batchResult = Database.Batch(commands, cts.Token);
                return GetMessageWithObject(batchResult);
            }
		}
开发者ID:kijanawoodard,项目名称:ravendb,代码行数:35,代码来源:DocumentsBatchController.cs

示例5: BulkDelete

		public HttpResponseMessage BulkDelete(string id)
		{
            using (var cts = new CancellationTokenSource())
            using (var timeout = cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatbaseOperationTimeout))
            {
                var databaseBulkOperations = new DatabaseBulkOperations(Database, GetRequestTransaction(), cts.Token, timeout);
                return OnBulkOperation(databaseBulkOperations.DeleteByIndex, id);
            }
		}
开发者ID:ReginaBricker,项目名称:ravendb,代码行数:9,代码来源:DocumentsBatchController.cs

示例6: BulkPost

        public async Task<HttpResponseMessage> BulkPost()
        {
            using (var cts = new CancellationTokenSource())
            using (cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
            {
                RavenJArray jsonCommandArray;

                try
                {
                    jsonCommandArray = await ReadJsonArrayAsync();
                }
                catch (InvalidOperationException e)
                {
                    Log.DebugException("Failed to deserialize document batch request." , e);
                    return GetMessageWithObject(new
                    {
                        Message = "Could not understand json, please check its validity."
                    }, (HttpStatusCode)422); //http code 422 - Unprocessable entity
                    
                }
                catch (InvalidDataException e)
                {
                    Log.DebugException("Failed to deserialize document batch request." , e);
                    return GetMessageWithObject(new
                    {
                        e.Message
                    }, (HttpStatusCode)422); //http code 422 - Unprocessable entity
                }

                cts.Token.ThrowIfCancellationRequested();

                var transactionInformation = GetRequestTransaction();
                var commands =
                    (from RavenJObject jsonCommand in jsonCommandArray select CommandDataFactory.CreateCommand(jsonCommand, transactionInformation)).ToArray();

                Log.Debug(
                    () =>
                    {
                        if (commands.Length > 15) // this is probably an import method, we will input minimal information, to avoid filling up the log
                        {
                            return "\tExecuted "
                                   + string.Join(
                                       ", ", commands.GroupBy(x => x.Method).Select(x => string.Format("{0:#,#;;0} {1} operations", x.Count(), x.Key)));
                        }

                        var sb = new StringBuilder();
                        foreach (var commandData in commands)
                        {
                            sb.AppendFormat("\t{0} {1}{2}", commandData.Method, commandData.Key, Environment.NewLine);
                        }
                        return sb.ToString();
                    });

                var batchResult = Database.Batch(commands, cts.Token);
                return GetMessageWithObject(batchResult);
            }
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:57,代码来源:DocumentsBatchController.cs

示例7: BulkPatch

		public async Task<HttpResponseMessage> BulkPatch(string id)
		{
            using (var cts = new CancellationTokenSource())
            using (var timeout = cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatbaseOperationTimeout))
            {
                var databaseBulkOperations = new DatabaseBulkOperations(Database, GetRequestTransaction(), cts.Token, timeout);
                var patchRequestJson = await ReadJsonArrayAsync();
                var patchRequests = patchRequestJson.Cast<RavenJObject>().Select(PatchRequest.FromJson).ToArray();
                return OnBulkOperation((index, query, allowStale) => databaseBulkOperations.UpdateByIndex(index, query, patchRequests, allowStale), id);
            }
		}
开发者ID:ReginaBricker,项目名称:ravendb,代码行数:11,代码来源:DocumentsBatchController.cs

示例8: Respond

		public override void Respond(IHttpContext context)
		{
			switch (context.Request.HttpMethod)
			{
				case "GET":
					long documentsCount = 0;
					Etag lastDocEtag = Etag.Empty;
					Database.TransactionalStorage.Batch(accessor =>
					{
						lastDocEtag = accessor.Staleness.GetMostRecentDocumentEtag();
						documentsCount = accessor.Documents.GetDocumentsCount();
					});

					lastDocEtag = lastDocEtag.HashWith(BitConverter.GetBytes(documentsCount));
					if (context.MatchEtag(lastDocEtag))
					{
						context.SetStatusToNotModified();
					}
					else
					{
						context.WriteHeaders(new RavenJObject(), lastDocEtag);

						using (var cts = new CancellationTokenSource())
						{
							cts.TimeoutAfter(Settings.DatbaseOperationTimeout);

							var startsWith = context.Request.QueryString["startsWith"];
							if (string.IsNullOrEmpty(startsWith))
								context.WriteJson(Database.GetDocuments(context.GetStart(), context.GetPageSize(Database.Configuration.MaxPageSize), context.GetEtagFromQueryString(), cts.Token));
							else
								context.WriteJson(Database.GetDocumentsWithIdStartingWith(
									startsWith,
									context.Request.QueryString["matches"],
									context.Request.QueryString["exclude"],
									context.GetStart(),
									context.GetPageSize(Database.Configuration.MaxPageSize), 
									cts.Token));
						}
					}
					break;
				case "POST":
					var json = context.ReadJson();
					var id = Database.Put(null, Etag.Empty, json,
					                      context.Request.Headers.FilterHeaders(),
					                      GetRequestTransaction(context));
					context.SetStatusToCreated("/docs/" + Uri.EscapeUriString(id.Key));
					context.WriteJson(id);
					break;
			}
		}
开发者ID:925coder,项目名称:ravendb,代码行数:50,代码来源:Docs.cs

示例9: DocsGet

		public HttpResponseMessage DocsGet()
		{
		    using (var cts = new CancellationTokenSource())
		    using (cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
		    {
		        long documentsCount = 0;
		        var lastDocEtag = Etag.Empty;
		        Database.TransactionalStorage.Batch(
		            accessor =>
		            {
		                lastDocEtag = accessor.Staleness.GetMostRecentDocumentEtag();
		                documentsCount = accessor.Documents.GetDocumentsCount();
		            });

		        lastDocEtag = lastDocEtag.HashWith(BitConverter.GetBytes(documentsCount));
		        if (MatchEtag(lastDocEtag)) return GetEmptyMessage(HttpStatusCode.NotModified);

		        var startsWith = GetQueryStringValue("startsWith");
		        HttpResponseMessage msg;
		        int nextPageStart = GetNextPageStart();
			    if (string.IsNullOrEmpty(startsWith))
			    {
				    var results = Database.Documents.GetDocuments(GetStart(), GetPageSize(Database.Configuration.MaxPageSize), 
						GetEtagFromQueryString(), cts.Token);
				    msg = GetMessageWithObject(results);
			    }
			    else
			    {
				    var transformer = GetQueryStringValue("transformer");
				    var transformerParameters = this.ExtractTransformerParameters();

				    msg =
					    GetMessageWithObject(
						    Database.Documents.GetDocumentsWithIdStartingWith(
							    startsWith,
							    GetQueryStringValue("matches"),
							    GetQueryStringValue("exclude"),
							    GetStart(),
							    GetPageSize(Database.Configuration.MaxPageSize),
							    cts.Token,
							    ref nextPageStart, transformer, transformerParameters,
								skipAfter: GetQueryStringValue("skipAfter")));
			    }

			    WriteHeaders(new RavenJObject { { Constants.NextPageStart, nextPageStart } }, lastDocEtag, msg);

		        return msg;
		    }
		}
开发者ID:jrusbatch,项目名称:ravendb,代码行数:49,代码来源:DocumentsController.cs

示例10: Respond

		public override void Respond(IHttpContext context)
		{
			using (context.Response.Streaming())
			{
				context.Response.ContentType = "application/json; charset=utf-8";

				var match = urlMatcher.Match(context.GetRequestUrl());
				var index = match.Groups[1].Value;

				var query = context.GetIndexQueryFromHttpContext(int.MaxValue);
				if (string.IsNullOrEmpty(context.Request.QueryString["pageSize"]))
					query.PageSize = int.MaxValue;
				var isHeadRequest = context.Request.HttpMethod == "HEAD";
				if (isHeadRequest)
					query.PageSize = 0;

				using (var writer = GetOutputWriter(context))
				{
					// we may be sending a LOT of documents to the user, and most 
					// of them aren't going to be relevant for other ops, so we are going to skip
					// the cache for that, to avoid filling it up very quickly
					using (DocumentCacher.SkipSettingDocumentsInDocumentCache())
					using (var cts = new CancellationTokenSource())
					using(var timeout = cts.TimeoutAfter(Settings.DatbaseOperationTimeout))
					{
						Database.Query(index, query, cts.Token, information =>
						{
							context.Response.AddHeader("Raven-Result-Etag", information.ResultEtag.ToString());
							context.Response.AddHeader("Raven-Index-Etag", information.IndexEtag.ToString());
							context.Response.AddHeader("Raven-Is-Stale", information.IsStable ? "true" : "false");
							context.Response.AddHeader("Raven-Index", information.Index);
							context.Response.AddHeader("Raven-Total-Results", information.TotalResults.ToString(CultureInfo.InvariantCulture));
							context.Response.AddHeader("Raven-Index-Timestamp",
													   information.IndexTimestamp.ToString(Default.DateTimeFormatsToWrite,
																						   CultureInfo.InvariantCulture));

							if (isHeadRequest)
								return;
							writer.WriteHeader();
						}, o =>
						{
							timeout.Delay();
                            Database.WorkContext.UpdateFoundWork();
							writer.Write(o);
						});
					}
				}
			}
		}
开发者ID:925coder,项目名称:ravendb,代码行数:49,代码来源:QueryStreams.cs

示例11: StreamToClient

        private void StreamToClient(Stream stream, string startsWith, int start, int pageSize, Etag etag, string matches, int nextPageStart, string skipAfter)
        {
            var bufferStream = new BufferedStream(stream, 1024 * 64);
            using (var cts = new CancellationTokenSource())
            using (var timeout = cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
            using (var writer = new JsonTextWriter(new StreamWriter(bufferStream)))
            {
                writer.WriteStartObject();
                writer.WritePropertyName("Results");
                writer.WriteStartArray();

                Action<JsonDocument> addDocument = doc =>
                {
                    timeout.Delay();
                    doc.ToJson().WriteTo(writer);
                    writer.WriteRaw(Environment.NewLine);
                };

                Database.TransactionalStorage.Batch(accessor =>
                {
                    // we may be sending a LOT of documents to the user, and most 
                    // of them aren't going to be relevant for other ops, so we are going to skip
                    // the cache for that, to avoid filling it up very quickly
                    using (DocumentCacher.SkipSettingDocumentsInDocumentCache())
                    {
                        if (string.IsNullOrEmpty(startsWith))
                        {
                            Database.Documents.GetDocuments(start, pageSize, etag, cts.Token, addDocument);
                        }
                        else
                        {
                            var nextPageStartInternal = nextPageStart;

                            Database.Documents.GetDocumentsWithIdStartingWith(startsWith, matches, null, start, pageSize, cts.Token, ref nextPageStartInternal, addDocument, skipAfter: skipAfter);

                            nextPageStart = nextPageStartInternal;
                        }
                    }
                });

                writer.WriteEndArray();
                writer.WritePropertyName("NextPageStart");
                writer.WriteValue(nextPageStart);
                writer.WriteEndObject();
                writer.Flush();
                bufferStream.Flush();
            }
        }
开发者ID:GorelH,项目名称:ravendb,代码行数:48,代码来源:StreamsController.cs

示例12: BulkDelete

		public HttpResponseMessage BulkDelete(string id)
		{
            // we don't use using because execution is async
		    var cts = new CancellationTokenSource();
		    var timeout = cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout);

	            var indexDefinition = Database.IndexDefinitionStorage.GetIndexDefinition(id);
				if (indexDefinition == null)
					throw new IndexDoesNotExistsException(string.Format("Index '{0}' does not exist.", id));

				if (indexDefinition.IsMapReduce)
					throw new InvalidOperationException("Cannot execute DeleteByIndex operation on Map-Reduce indexes.");


                var databaseBulkOperations = new DatabaseBulkOperations(Database, GetRequestTransaction(), cts, timeout);
            return OnBulkOperation(databaseBulkOperations.DeleteByIndex, id, cts, timeout);
            }
开发者ID:kijanawoodard,项目名称:ravendb,代码行数:17,代码来源:DocumentsBatchController.cs

示例13: IndexGet

		public HttpResponseMessage IndexGet(string id)
		{
            using (var cts = new CancellationTokenSource())
            using (cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
            {
                var index = id;
                if (string.IsNullOrEmpty(GetQueryStringValue("definition")) == false) 
                    return GetIndexDefinition(index);

                if (string.IsNullOrEmpty(GetQueryStringValue("source")) == false) 
                    return GetIndexSource(index);

                if (string.IsNullOrEmpty(GetQueryStringValue("debug")) == false) 
                    return DebugIndex(index);

                if (string.IsNullOrEmpty(GetQueryStringValue("explain")) == false) 
                    return GetExplanation(index);

                return GetIndexQueryResult(index, cts.Token);
            }
		}
开发者ID:cocytus,项目名称:ravendb,代码行数:21,代码来源:IndexController.cs

示例14: StreamToClient

        private void StreamToClient(Stream stream, ExportOptions options, Lazy<NameValueCollection> headers, IPrincipal user)
        {
            var old = CurrentOperationContext.Headers.Value;
            var oldUser = CurrentOperationContext.User.Value;
            try
            {
                CurrentOperationContext.Headers.Value = headers;
                CurrentOperationContext.User.Value = user;

                Database.TransactionalStorage.Batch(accessor =>
                {
                    var bufferStream = new BufferedStream(stream, 1024 * 64);

                    using (var cts = new CancellationTokenSource())
                    using (var timeout = cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
                    using (var streamWriter = new StreamWriter(bufferStream))
                    using (var writer = new JsonTextWriter(streamWriter))
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName("Results");
                        writer.WriteStartArray();

                        var exporter = new SmugglerExporter(Database, options);

                        exporter.Export(item => WriteToStream(writer, item, timeout), cts.Token);

                        writer.WriteEndArray();
                        writer.WriteEndObject();
                        writer.Flush();
                        bufferStream.Flush();
                    }
                });
            }
            finally
            {
                CurrentOperationContext.Headers.Value = old;
                CurrentOperationContext.User.Value = oldUser;
            }
        }
开发者ID:IdanHaim,项目名称:ravendb,代码行数:39,代码来源:SmugglerController.cs

示例15: IndexGet

		public HttpResponseMessage IndexGet(string id)
		{
            using (var cts = new CancellationTokenSource())
            using (cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
            {
                var index = id;
                if (string.IsNullOrEmpty(GetQueryStringValue("definition")) == false) 
                    return GetIndexDefinition(index);

                if (string.IsNullOrEmpty(GetQueryStringValue("source")) == false) 
                    return GetIndexSource(index);

                if (string.IsNullOrEmpty(GetQueryStringValue("debug")) == false) 
                    return DebugIndex(index);

                if (string.IsNullOrEmpty(GetQueryStringValue("explain")) == false) 
                    return GetExplanation(index);

                try
                {
                    return GetIndexQueryResult(index, cts.Token);
                }
                catch (OperationCanceledException e)
                {
                    throw new TimeoutException(string.Format("The query did not produce results in {0}", DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout), e);
                }
            }
		}
开发者ID:GorelH,项目名称:ravendb,代码行数:28,代码来源:IndexController.cs


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