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


C# CancellationToken.ThrowIfCancellationRequested方法代码示例

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


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

示例1: ImplementationAsync

        internal static async Task ImplementationAsync(Func<CancellationToken, Task> action, Context context, IEnumerable<ExceptionPredicate> shouldHandlePredicates, ICircuitController breakerController, CancellationToken cancellationToken, bool continueOnCapturedContext)
        {
            cancellationToken.ThrowIfCancellationRequested();

            breakerController.OnActionPreExecute();

            try
            {
                await action(cancellationToken).ConfigureAwait(continueOnCapturedContext);

                breakerController.OnActionSuccess(context);
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    if (ex is OperationCanceledException && ((OperationCanceledException) ex).CancellationToken == cancellationToken)
                    {
                        throw;
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                }

                if (!shouldHandlePredicates.Any(predicate => predicate(ex)))
                {
                    throw;
                }

                breakerController.OnActionFailure(ex, context);

                throw;
            }
        }
开发者ID:christopherbahr,项目名称:Polly,代码行数:33,代码来源:CircuitBreakerEngineAsync.cs

示例2: FindNavigableDeclaredSymbolInfos

        internal static async Task<IEnumerable<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>> FindNavigableDeclaredSymbolInfos(Project project, string pattern, CancellationToken cancellationToken)
        {
            var patternMatcher = new PatternMatcher(pattern);

            var result = new List<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>();
            foreach (var document in project.Documents)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var declaredSymbolInfos = await document.GetDeclaredSymbolInfosAsync(cancellationToken).ConfigureAwait(false);
                foreach (var declaredSymbolInfo in declaredSymbolInfos)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var patternMatches = patternMatcher.GetMatches(
                        GetSearchName(declaredSymbolInfo),
                        declaredSymbolInfo.FullyQualifiedContainerName,
                        includeMatchSpans: false);

                    if (patternMatches != null)
                    {
                        result.Add(ValueTuple.Create(declaredSymbolInfo, document, patternMatches));
                    }
                }
            }

            return result;
        }
开发者ID:swaroop-sridhar,项目名称:roslyn,代码行数:26,代码来源:NavigateToSymbolFinder.cs

示例3: ComputeOperationsAsync

        protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var previewDialogService = _workspace.Services.GetService<IPreviewDialogService>();
            if (previewDialogService == null)
            {
                return null;
            }

            var changedSolution = previewDialogService.PreviewChanges(
                EditorFeaturesResources.PreviewChanges,
                "vs.codefix.previewchanges",
                _originalCodeAction.Title,
                EditorFeaturesResources.PreviewChangesRootNodeText,
                CodeAnalysis.Glyph.OpenFolder,
                _changeSummary.NewSolution,
                _changeSummary.OldSolution,
                showCheckBoxes: false);

            if (changedSolution == null)
            {
                // User pressed the cancel button.
                return null;
            }

            cancellationToken.ThrowIfCancellationRequested();
            return await _originalCodeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false);
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:28,代码来源:PreviewChangesCodeAction.cs

示例4: LoadAsync

            async Task LoadAsync(int carId, String url, string userAgent, CancellationToken cancel)
            {
                var handler = new HttpClientHandler { AllowAutoRedirect = false };
                var http = new HttpClient(handler);
                http.DefaultRequestHeaders.Add("User-Agent", userAgent );



                //Get a correct URL from the given one (e.g. transform codeproject.com to http://codeproject.com)
                var uri = Sanitize(url);

                //Make the request
                var request = await http.GetAsync(uri);
                //var request = await http.GetStringAsync(uri);
                cancel.ThrowIfCancellationRequested();

                //Get the response stream
                var response = await request.Content.ReadAsStringAsync();
                cancel.ThrowIfCancellationRequested();
                var html = new Html
                {
                    CarId = carId,
                    html = response,
                    Processed = false
                };
                var data = new Data();
                data.InsertHtmlData(html);
                cancel.ThrowIfCancellationRequested();

                /* Use the document */
            }
开发者ID:wcrowe,项目名称:CarCrawler,代码行数:31,代码来源:Program.cs

示例5: GetAllProjectCollections

        /// <summary>
        /// Gets all project collections.
        /// </summary>
        /// <param name="client">The <see cref="ProjectCollectionHttpClient"/> to use.</param>
        /// <param name="pageSize">Page size to use while retrieving Project Collections.</param>
        /// <param name="userState">The user state object.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public static async Task<IList<TeamProjectCollection>> GetAllProjectCollections(this ProjectCollectionHttpClient client, int pageSize = 10, object userState = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (client == null) throw new ArgumentNullException(nameof(client));
            if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize));
            
            var result = new List<TeamProjectCollection>();

            int currentPage = 0;
            var currentProjectCollectionReferences = (await client.GetProjectCollections(pageSize, currentPage, userState).ConfigureAwait(false)).ToList();
            while (currentProjectCollectionReferences.Count > 0)
            {
                foreach (var projectCollectionReference in currentProjectCollectionReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    result.Add(await client.GetProjectCollection(projectCollectionReference.Id, userState).ConfigureAwait(false));
                }
                
                // check whether the recently returned item(s) were less than the max page size
                if (currentProjectCollectionReferences.Count < pageSize)
                    break; // if so, break the loop as we've read all instances

                // otherwise continue
                cancellationToken.ThrowIfCancellationRequested();
                currentProjectCollectionReferences = (await client.GetProjectCollections(pageSize, currentPage++, userState).ConfigureAwait(false)).ToList();
            }

            cancellationToken.ThrowIfCancellationRequested();
            return result;
        }
开发者ID:jbattermann,项目名称:JB.Common,代码行数:39,代码来源:ProjectCollectionHttpClientExtensions.cs

示例6: FindReferences

		IEnumerable<SharpTreeNode> FindReferences(LoadedAssembly asm, CancellationToken ct)
		{
			string name = analyzedField.Name;
			string declTypeName = analyzedField.DeclaringType.FullName;
			foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.AssemblyDefinition.MainModule.Types, t => t.NestedTypes)) {
				ct.ThrowIfCancellationRequested();
				foreach (MethodDefinition method in type.Methods) {
					ct.ThrowIfCancellationRequested();
					bool found = false;
					if (!method.HasBody)
						continue;
					foreach (Instruction instr in method.Body.Instructions) {
						if (CanBeReference(instr.OpCode.Code)) {
							FieldReference fr = instr.Operand as FieldReference;
							if (fr != null && fr.Name == name && fr.DeclaringType.FullName == declTypeName && fr.Resolve() == analyzedField) {
								found = true;
								break;
							}
						}
					}
					if (found)
						yield return new AnalyzedMethodTreeNode(method);
				}
			}
		}
开发者ID:hlesesne,项目名称:ILSpy,代码行数:25,代码来源:AnalyzedFieldAccessNode.cs

示例7: FindReferences

		IEnumerable<SharpTreeNode> FindReferences(LoadedAssembly asm, CancellationToken ct)
		{
			string asmName = asm.AssemblyDefinition.Name.Name;
			string name = analyzedMethod.Name;
			string declTypeName = analyzedMethod.DeclaringType.FullName;
			foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.AssemblyDefinition.MainModule.Types, t => t.NestedTypes))
			{
				ct.ThrowIfCancellationRequested();
				SharpTreeNode newNode = null;
				try {
					if (!TypesHierarchyHelpers.IsBaseType(analyzedMethod.DeclaringType, type, resolveTypeArguments: false))
						continue;

					foreach (MethodDefinition method in type.Methods) {
						ct.ThrowIfCancellationRequested();

						if (TypesHierarchyHelpers.IsBaseMethod(analyzedMethod, method)) {
							bool hidesParent = !method.IsVirtual ^ method.IsNewSlot;
							newNode = new AnalyzedMethodTreeNode(method, hidesParent ? "(hides) " : "");
						}
					}
				}
				catch (ReferenceResolvingException) {
					// ignore this type definition. maybe add a notification about such cases.
				}
				if (newNode != null)
					yield return newNode;
			}
		}
开发者ID:tris2481,项目名称:ILSpy,代码行数:29,代码来源:AnalyzerMethodOverridesTreeNode.cs

示例8: FixEFModelAsync

        private async Task<Solution> FixEFModelAsync(Project project, Compilation compilation,
            IEnumerable<IClassAssumption> classAssumptions, IEnumerable<IPropertyAssumption> propertyAssumptions, ObjectTheoremResult objectTheoremResult,
            CancellationToken cancellationToken)
        {
            Trace.WriteLine("FixEFModelAsync");
            try
            {
                var newSolution = project.Solution;

                foreach (var syntaxTree in compilation.SyntaxTrees)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var syntaxRoot = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
                    var semanticModel = compilation.GetSemanticModel(syntaxTree);

                    var rewriter = new AttributeAssumptionsRewriter(semanticModel, classAssumptions, propertyAssumptions, objectTheoremResult, cancellationToken);
                    var newSyntaxRoot = rewriter.Visit(syntaxRoot);

                    cancellationToken.ThrowIfCancellationRequested();

                    var documentId = newSolution.GetDocumentId(syntaxTree);
                    newSolution = newSolution.WithDocumentSyntaxRoot(documentId, newSyntaxRoot);
                }

                return newSolution;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw;
            }
        }
开发者ID:RicardoNiepel,项目名称:Z3.ObjectTheorem,代码行数:33,代码来源:CodeFixProvider.cs

示例9: SearchAsync

        private async Task<ImmutableArray<INavigateToSearchResult>> SearchAsync(
             Func<INavigateToSearchResultProvider, Task<ImmutableArray<INavigateToSearchResult>>> searchAsync,
             CancellationToken cancellationToken)
        {
            var tasks = new Task<ImmutableArray<INavigateToSearchResult>>[_resultProviders.Length];
            for (int i = 0; i < _resultProviders.Length; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var resultProvider = _resultProviders[i];
                tasks[i] = searchAsync(resultProvider);
            }

            await Task.WhenAll(tasks).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            var results = ArrayBuilder<INavigateToSearchResult>.GetInstance();
            foreach (var task in tasks)
            {
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    results.AddRange(task.Result);
                }
            }

            return results.ToImmutableAndFree();
        }
开发者ID:natidea,项目名称:roslyn,代码行数:28,代码来源:AbstractNavigateToSearchService.cs

示例10: GetPackageStream

        /// <summary>
        /// Sets <param name="targetPackageStream"></param> for a given <param name="packageIdentity"></param> 
        /// from the given <param name="sourceRepository"></param>. If successfully set, returns true. Otherwise, false
        /// </summary>
        public static async Task<bool> GetPackageStream(SourceRepository sourceRepository, PackageIdentity packageIdentity, Stream targetPackageStream, CancellationToken token)
        {
            // TODO: Tie up machine cache with CacheClient?!

            try
            {
                token.ThrowIfCancellationRequested();
                // Step-1 : Get the download stream for packageIdentity
                Stream downloadStream = await GetDownloadStream(sourceRepository, packageIdentity, token);

                if(downloadStream == null)
                {
                    return false;
                }

                token.ThrowIfCancellationRequested();
                // Step-2: Copy download stream to targetPackageStream if it is not null
                await downloadStream.CopyToAsync(targetPackageStream);
                return true;
            }
            catch (Exception)
            {
                return false;
            } 
        }
开发者ID:pabomex,项目名称:NuGet.PackageManagement,代码行数:29,代码来源:PackageDownloader.cs

示例11: Execute

        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await session.Inventory.RefreshCachedInventory();

            var pokemons = await session.Inventory.GetPokemons();

            foreach (var pokemon in pokemons)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var perfection = Math.Round(PokemonInfo.CalculatePokemonPerfection(pokemon));

                if (session.LogicSettings.AutoFavoritePokemon && perfection >= session.LogicSettings.FavoriteMinIvPercentage && pokemon.Favorite!=1)
                {
                    await session.Client.Inventory.SetFavoritePokemon(pokemon.Id, true);

                    session.EventDispatcher.Send(new NoticeEvent
                    {
                        Message =
                            session.Translation.GetTranslation(TranslationString.PokemonFavorite, perfection, session.Translation.GetPokemonTranslation(pokemon.PokemonId), pokemon.Cp)
                    });
                }
            }
        }
开发者ID:ChronoXNL,项目名称:NecroBot,代码行数:25,代码来源:FavoritePokemonTask.cs

示例12: Start

        public void Start(CancellationToken token)
        {
            try
            {
                var code = RewriteAndPreprocess();
                token.ThrowIfCancellationRequested();

                var attributes = _attributeParser.Parse(_component);

                token.ThrowIfCancellationRequested();

                // temporal coupling... comments must be acquired before we walk the parse tree for declarations
                // otherwise none of the annotations get associated to their respective Declaration
                var commentListener = new CommentListener();
                var annotationListener = new AnnotationListener(new VBAParserAnnotationFactory(), _qualifiedName);

                var stopwatch = Stopwatch.StartNew();
                ITokenStream stream;
                var tree = ParseInternal(code, new IParseTreeListener[]{ commentListener, annotationListener }, out stream);
                stopwatch.Stop();
                if (tree != null)
                {
                    Debug.Print("IParseTree for component '{0}' acquired in {1}ms (thread {2})", _component.Name, stopwatch.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId);
                }

                var comments = QualifyAndUnionComments(_qualifiedName, commentListener.Comments, commentListener.RemComments);
                token.ThrowIfCancellationRequested();

                ParseCompleted.Invoke(this, new ParseCompletionArgs
                {
                    ParseTree = tree,
                    Tokens = stream,
                    Attributes = attributes,
                    Comments = comments,
                    Annotations = annotationListener.Annotations
                });
            }
            catch (COMException exception)
            {
                Debug.WriteLine("Exception thrown in thread {0}:\n{1}", Thread.CurrentThread.ManagedThreadId, exception);
                ParseFailure.Invoke(this, new ParseFailureArgs
                {
                    Cause = exception
                });
            }
            catch (SyntaxErrorException exception)
            {
                Debug.WriteLine("Exception thrown in thread {0}:\n{1}", Thread.CurrentThread.ManagedThreadId, exception);
                ParseFailure.Invoke(this, new ParseFailureArgs
                {
                    Cause = exception
                });
            }
            catch (OperationCanceledException cancel)
            {
                Debug.WriteLine("Operation was Cancelled", cancel);
                // no results to be used, so no results "returned"
                //ParseCompleted.Invoke(this, new ParseCompletionArgs());
            }
        }
开发者ID:retailcoder,项目名称:Rubberduck,代码行数:60,代码来源:ComponentParseTask.cs

示例13: CopyAsync

 public static Task CopyAsync(string sourceFileName, string destFileName, CancellationToken token, IProgress<double> progress)
 {
     int pbCancel = 0;
     CopyProgressRoutine copyProgressHandler;
     if (progress != null)
     {
         copyProgressHandler = (total, transferred, streamSize, streamByteTrans, dwStreamNumber, reason, hSourceFile, hDestinationFile, lpData) =>
         {
             progress.Report((double)transferred / total * 100);
             return CopyProgressResult.PROGRESS_CONTINUE;
         };
     }
     else
     {
         copyProgressHandler = EmptyCopyProgressHandler;
     }
     token.ThrowIfCancellationRequested();
     var ctr = token.Register(() => pbCancel = 1);
     var copyTask = Task.Run(() =>
     {
         try
         {
             CopyFileEx(sourceFileName, destFileName, copyProgressHandler, IntPtr.Zero, ref pbCancel, CopyFileFlags.COPY_FILE_RESTARTABLE);
             token.ThrowIfCancellationRequested();
         }
         finally
         {
             ctr.Dispose();
         }
     }, token);
     return copyTask;
 }
开发者ID:webnoob,项目名称:KHPlayer,代码行数:32,代码来源:CopyFileEx.cs

示例14: LoadAsync

        private async Task LoadAsync(String url, CancellationToken cancel)
        {
            var handler = new HttpClientHandler {AllowAutoRedirect = false};
            var http = new HttpClient(handler);
            http.DefaultRequestHeaders.Add("User-Agent",
                "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");



            //Get a correct URL from the given one (e.g. transform codeproject.com to http://codeproject.com)
            var uri = Sanitize(url);

            //Make the request
            var request = await http.GetAsync(uri);
            //var request = await http.GetStringAsync(uri);
            cancel.ThrowIfCancellationRequested();

            //Get the response stream
            var response = await request.Content.ReadAsStringAsync();
            cancel.ThrowIfCancellationRequested();
            var html = new Html();
            txtHtml.Text = response;
            html.CarId = Convert.ToInt32(textBox1.Text);
            html.html = response;
            html.Processed = false;
            var data = new Data();
            data.InsertHtmlData(html);
            cancel.ThrowIfCancellationRequested();

            /* Use the document */
        }
开发者ID:wcrowe,项目名称:CarCrawler,代码行数:31,代码来源:mainForm.cs

示例15: fromStorageFile

        // Fetches all the data for the specified file
        public async static Task<FileItem> fromStorageFile(StorageFile f, CancellationToken ct)
        {
            FileItem item = new FileItem();
            item.Filename = f.DisplayName;
            
            // Block to make sure we only have one request outstanding
            await gettingFileProperties.WaitAsync();

            BasicProperties bp = null;
            try
            {
                bp = await f.GetBasicPropertiesAsync().AsTask(ct);
            }
            catch (Exception) { }
            finally
            {
                gettingFileProperties.Release();
            }

            ct.ThrowIfCancellationRequested();

            item.Size = (int)bp.Size;
            item.Key = f.FolderRelativeId;

            StorageItemThumbnail thumb = await f.GetThumbnailAsync(ThumbnailMode.SingleItem).AsTask(ct);
            ct.ThrowIfCancellationRequested();
            BitmapImage img = new BitmapImage();
            await img.SetSourceAsync(thumb).AsTask(ct);

            item.ImageData = img;
            return item;
        }
开发者ID:C-C-D-I,项目名称:Windows-universal-samples,代码行数:33,代码来源:FileItem.cs


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