本文整理汇总了C#中System.Threading.CancellationToken类的典型用法代码示例。如果您正苦于以下问题:C# CancellationToken类的具体用法?C# CancellationToken怎么用?C# CancellationToken使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CancellationToken类属于System.Threading命名空间,在下文中一共展示了CancellationToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetChannelStreamMediaSources
protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, string channelId, CancellationToken cancellationToken)
{
var urlHash = info.Url.GetMD5().ToString("N");
var prefix = ChannelIdPrefix + urlHash;
if (!channelId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return null;
}
var channels = await GetChannels(info, true, cancellationToken).ConfigureAwait(false);
var m3uchannels = channels.Cast<M3UChannel>();
var channel = m3uchannels.FirstOrDefault(c => string.Equals(c.Id, channelId, StringComparison.OrdinalIgnoreCase));
if (channel != null)
{
var path = channel.Path;
MediaProtocol protocol = MediaProtocol.File;
if (path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
protocol = MediaProtocol.Http;
}
else if (path.StartsWith("rtmp", StringComparison.OrdinalIgnoreCase))
{
protocol = MediaProtocol.Rtmp;
}
else if (path.StartsWith("rtsp", StringComparison.OrdinalIgnoreCase))
{
protocol = MediaProtocol.Rtsp;
}
var mediaSource = new MediaSourceInfo
{
Path = channel.Path,
Protocol = protocol,
MediaStreams = new List<MediaStream>
{
new MediaStream
{
Type = MediaStreamType.Video,
// Set the index to -1 because we don't know the exact index of the video stream within the container
Index = -1,
IsInterlaced = true
},
new MediaStream
{
Type = MediaStreamType.Audio,
// Set the index to -1 because we don't know the exact index of the audio stream within the container
Index = -1
}
},
RequiresOpening = false,
RequiresClosing = false,
ReadAtNativeFramerate = true
};
return new List<MediaSourceInfo> { mediaSource };
}
return new List<MediaSourceInfo>();
}
示例2: RemoveAllRenameAnnotationsAsync
internal async Task RemoveAllRenameAnnotationsAsync(IEnumerable<DocumentId> documentWithRenameAnnotations, AnnotationTable<RenameAnnotation> annotationSet, CancellationToken cancellationToken)
{
foreach (var documentId in documentWithRenameAnnotations)
{
if (_renamedSpansTracker.IsDocumentChanged(documentId))
{
var document = _newSolution.GetDocument(documentId);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// For the computeReplacementToken and computeReplacementNode functions, use
// the "updated" node to maintain any annotation removals from descendants.
var newRoot = root.ReplaceSyntax(
nodes: annotationSet.GetAnnotatedNodes(root),
computeReplacementNode: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
tokens: annotationSet.GetAnnotatedTokens(root),
computeReplacementToken: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(),
computeReplacementTrivia: null);
_intermediateSolutionContainingOnlyModifiedDocuments = _intermediateSolutionContainingOnlyModifiedDocuments.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity);
}
}
_newSolution = _intermediateSolutionContainingOnlyModifiedDocuments;
}
示例3: PeekAsync
public async Task<bool> PeekAsync(CancellationToken cancellationToken)
{
//If we already have a byte read but not consumed, do nothing.
if (_hasPeekByte)
{
return true;
}
//If transport closed we can't peek.
if (!IsOpen)
{
return false;
}
//Try to read one byte. If succeeds we will need to store it for the next read.
try
{
var bytes = await ReadAsync(_peekBuffer, 0, 1, cancellationToken);
if (bytes == 0)
{
return false;
}
}
catch (IOException)
{
return false;
}
_hasPeekByte = true;
return true;
}
示例4: Start
public async Task Start(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Settings.Default.Reload();
var imageInfo = GetLatestImageInfo();
if (imageInfo != null)
{
var image = AssembleImageFrom(imageInfo);
var imageFile = SaveImage(image);
Wallpaper.Set(imageFile, Wallpaper.Style.Fit);
}
if (Settings.Default.Interval > 0)
{
_internalTokenSource = new CancellationTokenSource();
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, token))
{
try
{
await Task.Delay(TimeSpan.FromMinutes(Settings.Default.Interval), linkedCts.Token);
}
catch
{
// ignore exception raised by token cancellation
}
}
}
}
}
示例5: Run
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
{
var users = _userManager.Users
.DistinctBy(ChannelDownloadScheduledTask.GetUserDistinctValue)
.Select(i => i.Id.ToString("N"))
.ToList();
var numComplete = 0;
foreach (var user in users)
{
double percentPerUser = 1;
percentPerUser /= users.Count;
var startingPercent = numComplete * percentPerUser * 100;
var innerProgress = new ActionableProgress<double>();
innerProgress.RegisterAction(p => progress.Report(startingPercent + (percentPerUser * p)));
await DownloadContent(user, cancellationToken, innerProgress).ConfigureAwait(false);
numComplete++;
double percent = numComplete;
percent /= users.Count;
progress.Report(percent * 100);
}
progress.Report(100);
}
示例6: VerifyFixInternalAsync
private async Task VerifyFixInternalAsync(string language, ImmutableArray<DiagnosticAnalyzer> analyzers, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex,
bool allowNewCompilerDiagnostics, int maxNumberOfIterations, Func<ImmutableArray<DiagnosticAnalyzer>, CodeFixProvider, int?, CancellationToken, Document, int, Task<Document>> getFixedDocument, CancellationToken cancellationToken)
{
var document = this.CreateDocument(oldSource, language);
var compilerDiagnostics = await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false);
document = await getFixedDocument(analyzers, codeFixProvider, codeFixIndex, cancellationToken, document, maxNumberOfIterations).ConfigureAwait(false);
var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false));
// check if applying the code fix introduced any new compiler diagnostics
if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
{
// Format and get the compiler diagnostics again so that the locations make sense in the output
document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false));
string message =
string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
(await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).ToFullString());
Assert.True(false, message);
}
// after applying all of the code fixes, compare the resulting string to the inputted one
var actual = await GetStringFromDocumentAsync(document, cancellationToken).ConfigureAwait(false);
Assert.Equal(newSource, actual);
}
示例7: ExecuteBindingAsync
public override Task ExecuteBindingAsync(Controllers.HttpActionContext actionContext, CancellationToken cancellationToken)
{
return _traceWriter.TraceBeginEndAsync(
actionContext.ControllerContext.Request,
TraceCategories.ModelBindingCategory,
TraceLevel.Info,
_innerBinding.GetType().Name,
ExecuteBindingAsyncMethodName,
beginTrace: null,
execute: () => _innerBinding.ExecuteBindingAsync(actionContext, cancellationToken),
endTrace: (tr) =>
{
if (!actionContext.ModelState.IsValid)
{
tr.Message = Error.Format(SRResources.TraceModelStateInvalidMessage,
FormattingUtilities.ModelStateToString(
actionContext.ModelState));
}
else
{
if (actionContext.ActionDescriptor.GetParameters().Count > 0)
{
tr.Message = Error.Format(SRResources.TraceValidModelState,
FormattingUtilities.ActionArgumentsToString(
actionContext.ActionArguments));
}
}
},
errorTrace: null);
}
示例8: MakeMock
private static async Task<Document> MakeMock(Document document, SyntaxNode invokationSyntax,
CancellationToken cancellationToken)
{
var testSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var testInitMethodDecl = TestSemanticHelper.GetTestInitializeMethod(testSemanticModel);
var declaredFields = testInitMethodDecl.Parent.ChildNodes().OfType<FieldDeclarationSyntax>().ToArray();
var suts = testInitMethodDecl.GetSuts(testSemanticModel, declaredFields);
var memberAccessExpressions = invokationSyntax.DescendantNodes()
.OfType<ExpressionSyntax>()
.Where(x => x is InvocationExpressionSyntax || x is MemberAccessExpressionSyntax)
.Select(expr =>
{
var memberAccess = expr as MemberAccessExpressionSyntax;
var invokationExpression = expr as InvocationExpressionSyntax;
var expression = invokationExpression == null ? memberAccess : invokationExpression.Expression;
return expression;
});
var invokedMethodsOfMocks = memberAccessExpressions.SelectMany(expressionSyntax => MocksAnalyzingEngine.GetInvokedMethodsOfMock(expressionSyntax, testSemanticModel, suts))
.DistinctBy(x => string.Join(",", x.FieldsToSetup.SelectMany(y => y.Field.Select(z => z))) + "," + x.MethodOrPropertySymbol)
.ToArray();
if (invokedMethodsOfMocks.Length == 0)
return document;
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
ChangesMaker.ApplyChanges(invokationSyntax, editor, invokedMethodsOfMocks);
return editor.GetChangedDocument();
}
示例9: OnAuthorizationAsync
public override async Task OnAuthorizationAsync( HttpActionContext actionContext, CancellationToken cancellationToken )
{
if ( actionContext.ControllerContext.ControllerDescriptor.ControllerType == typeof( UserController ) || string.Equals( actionContext.ActionDescriptor.ActionName, "Test", StringComparison.OrdinalIgnoreCase ) )
return;
var request = actionContext.Request;
string loginToken = null;
if ( loginToken == null )
{
var authorization = request.Headers.Authorization;
if ( authorization != null && authorization.Scheme == "Hello" )
loginToken = authorization.Parameter;
}
if ( loginToken == null )
{
var cookie = request.Headers.GetCookies( "loginToken" ).SelectMany( c => c.Cookies );
if ( cookie.Any() )
loginToken = cookie.First().Value;
}
var userId = Host.UserService.GetUserID( loginToken );
if ( userId == null )
actionContext.Response = request.CreateErrorResponse( HttpStatusCode.Unauthorized, "Unauthorized" );
else
actionContext.Request.Properties["UserID"] = userId;
}
示例10: IsExtensionMethodParameterContext
private static bool IsExtensionMethodParameterContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// TODO(cyrusn): lambda/anon methods can have out/ref parameters
if (!context.SyntaxTree.IsParameterModifierContext(context.Position, context.LeftToken, cancellationToken, allowableIndex: 0))
{
return false;
}
var token = context.LeftToken;
var method = token.GetAncestor<MethodDeclarationSyntax>();
var typeDecl = method.GetAncestorOrThis<TypeDeclarationSyntax>();
if (method == null || typeDecl == null)
{
return false;
}
if (typeDecl.Kind() != SyntaxKind.ClassDeclaration)
{
return false;
}
if (!method.Modifiers.Any(t => t.Kind() == SyntaxKind.StaticKeyword))
{
return false;
}
if (!typeDecl.Modifiers.Any(t => t.Kind() == SyntaxKind.StaticKeyword))
{
return false;
}
return true;
}
示例11: GetRefactoringsAsync
public async Task<IEnumerable<CodeAction>> GetRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(textSpan);
var switchStatementNode = node as SwitchStatementSyntax;
if (switchStatementNode == null)
return null;
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var memberEx = switchStatementNode.Expression as MemberAccessExpressionSyntax;
if (memberEx == null)
return null;
var symbolInfo = semanticModel.GetTypeInfo(memberEx.Name);
var enumTypeInfo = symbolInfo.Type;
if (enumTypeInfo.TypeKind != TypeKind.Enum)
return null;
var enumName = enumTypeInfo.Name;
var nameSpace = enumTypeInfo.ContainingNamespace.Name;
var enumType = Type.GetType(nameSpace + "." + enumName);
if (enumType == null)
return null;
return new[] { CodeAction.Create("Explode Switch", c => ExplodeSwitch(document, root, semanticModel, switchStatementNode, c)) };
}
示例12: GeneratePasswords
//probe==StartBounder
public bool GeneratePasswords(int[] probe, int[] startBoundary, int[] endBoundary, int depth, int range, CancellationToken ct, CancellationTokenSource tokenSource, Action<string> sendPassword)
{
bool result = false;
char[] probeChar = CharForThread(probe, _options);
string probeString = String.Join("", probeChar);
if (depth==0)
{
Console.WriteLine(probeString);
if (VerifyMd5Hash(probeString))
{
Password = probeString;
sendPassword(Password);
return true;
}
return false;
}
if (ct.IsCancellationRequested)
{
Console.WriteLine("Task is canceled");
}
if (probe.SequenceEqual(endBoundary)) return false;
for (int i = 0; i < range; i++)
{
probe[depth - 1] = i;
result = GeneratePasswords(probe, startBoundary, endBoundary, depth - 1, range, ct, tokenSource, sendPassword);
if (result) break;
}
return result;
}
示例13: IsValidContext
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
IsInstanceExpressionOrStatement(context) ||
IsExtensionMethodParameterContext(context, cancellationToken) ||
IsConstructorInitializerContext(context);
}
示例14: TryInitializeState
protected override bool TryInitializeState(
Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
{
var baseClassNode = node as TypeSyntax;
if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
{
if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
{
abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
cancellationToken.ThrowIfCancellationRequested();
if (abstractClassType.IsAbstractClass())
{
var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;
return classType != null && abstractClassType != null;
}
}
}
classType = null;
abstractClassType = null;
return false;
}
示例15: TokenAsync
public async Task<Token> TokenAsync(string code, CancellationToken cancellationToken = default(CancellationToken))
{
var token = await _requestExecuter.Execute<Token>(() => _requestGenerator.AccessToken(_options.ClientId, _options.ClientSecret, _options.RedirectUri, code), cancellationToken: cancellationToken).ConfigureAwait(false);
_options.AccessToken = token.access_token;
return token;
}