protected override void AnnotateCorpus( Corpus corpus, System.Threading.CancellationToken token) { token.ThrowIfCancellationRequested(); Guid taskId = Guid.NewGuid(); DirectoryInfo dir = new DirectoryInfo( AppDomain.CurrentDomain.BaseDirectory); dir = dir.CreateSubdirectory("Tasks"); dir = dir.CreateSubdirectory(taskId.ToString()); string dataFile = dir.FullName + "\\Corpus.crfppdata"; string outputFile = dir.FullName + "\\Output.crfppdata"; try { AnnotationProgressChangedEventArgs ePrepared = new AnnotationProgressChangedEventArgs( 1, 3, MessagePreparing); OnAnnotationProgressChanged(ePrepared); CRFPPHelper.EncodeCorpusToCRFPPData(corpus, dataFile); token.ThrowIfCancellationRequested(); AnnotationProgressChangedEventArgs eAnnotating = new AnnotationProgressChangedEventArgs( 2, 3, MessageAnnotating); OnAnnotationProgressChanged(eAnnotating); CRFPPHelper.Annotate( Model.RootPath, dataFile, outputFile, 1, 0); token.ThrowIfCancellationRequested(); AnnotationProgressChangedEventArgs eFinishing = new AnnotationProgressChangedEventArgs( 3, 3, MessageFinishing); OnAnnotationProgressChanged(eFinishing); CRFPPHelper.DecodeCorpusFromCRFPPData(corpus, outputFile); token.ThrowIfCancellationRequested(); } catch { throw; } finally { File.Delete(dataFile); File.Delete(outputFile); try { dir.Delete(); } catch { } } }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var response = responseCreator(request); response.RequestMessage = request; return Task.FromResult(response); }
private ICollection<CsprojFileData> FindCsprojFiles(System.Threading.CancellationToken cancellationToken, IProgress<DiscoveryProgress> progress) { var files = new List<CsprojFileData>(); // find csproj files foreach (var fileName in System.IO.Directory.EnumerateFiles(FolderPath, "*.csproj", System.IO.SearchOption.AllDirectories)) { cancellationToken.ThrowIfCancellationRequested(); progress.Report(new DiscoveryProgress() { CurrentItem = fileName }); CsprojFileData csprojData = null; try { csprojData = csprojFileReader.ReadFromFile(fileName); } catch (Exception e) { Debug.WriteLine("Error reading CSPROJ: " + e.Message); } if (csprojData != null) files.Add(csprojData); } return files; }
public Task<GraphData> Resolve(System.Threading.CancellationToken cancellationToken, IProgress<DiscoveryProgress> progress) { return Task.Factory.StartNew<GraphData>(() => { // read *.csproj projects var projects = FindCsprojFiles(cancellationToken, progress); cancellationToken.ThrowIfCancellationRequested(); // read *.sln files var solutions = FindSlnFiles(cancellationToken, progress); cancellationToken.ThrowIfCancellationRequested(); // build result var result = builder.Build(this, projects, solutions); return result; }); }
/// <summary> /// Calculates the sequence to a specified length. /// </summary> /// <param name="length">The length to calculate.</param> /// <param name="cancellationToken">The cancellation token used to cancel the work.</param> /// <param name="progress">The progress reporting object. Each report specifies the value of a single element.</param> /// <returns> /// Sequence results. /// </returns> public async Task CalculateAsync(int length, System.Threading.CancellationToken cancellationToken, IProgress<int> progress) { List<int> results = new List<int>(); for (int loopVariable = 0; loopVariable < length; loopVariable++) { int index = loopVariable; // create a continuation to run asynchronously (probably the thread pool) await Task.Run( () => { // check the cancellation token to see if cancellation is required cancellationToken.ThrowIfCancellationRequested(); // the first two elements are not calculated if (index < 2) { results.Add(index); } else { // the new element is (i-1 + i-2) results.Add(results[results.Count - 1] + results[results.Count - 2]); } if (results.Last() % 2 == 0) { //throw new InvalidOperationException("Test Exception"); } System.Threading.Thread.Sleep(500); // check the cancellation token to see if cancellation is required cancellationToken.ThrowIfCancellationRequested(); progress.Report(results.Last()); }); var handler = this.OnStepAdvance; if (handler != null) { handler(this, new StepEventArgs(results.Last())); } } }
public async Task<bool> VerifyPaymentAsync(string identifier, decimal? expectedAmount, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { if(String.IsNullOrEmpty(Account)) { throw new InvalidOperationException("The Account property must be set before calling VerifyPaymentAsync"); } if(String.IsNullOrEmpty(User)) { throw new InvalidOperationException("The User property must be set before calling VerifyPaymentAsync"); } if(String.IsNullOrEmpty(Password)) { throw new InvalidOperationException("The Password property must be set before calling VerifyPaymentAsync"); } var rangeEnd = DateTime.Now.AddDays(1); var rangeStart = rangeEnd.AddDays(-7); var data = new Dictionary<string, string> { {"ShopOrderNumber", identifier },// ReferenceCalculator.GenerateReferenceNumber(identifier)}, {"Shop_Id", Account}, {"Login", User}, {"Password", Password}, {"Format", "1"}, {"English", "1"}, {"StartYear", rangeStart.Year.ToString() }, {"StartMonth", rangeStart.Month.ToString() }, {"StartDay", rangeStart.Day.ToString() }, {"StartHour", "0"}, {"StartMin", "0"}, {"EndYear", rangeEnd.Year.ToString() }, {"EndMonth", rangeEnd.Month.ToString() }, {"EndDay", rangeEnd.Day.ToString() }, {"EndHour", "0"}, {"EndMin", "0"} }; // Make request var client = new HttpClient(); var response = await client.PostAsync(EndpointUrl, new FormUrlEncodedContent(data), cancellationToken); response.EnsureSuccessStatusCode(); cancellationToken.ThrowIfCancellationRequested(); var responseContent = await response.Content.ReadAsStringAsync(); // Match successful payment if(responseContent.Contains(identifier+";AS000;SUCCESSFUL")) { return true; } // Match payment outside date interval if(responseContent.Contains("ERROR:")) { return false; } // Match various error codes for unsuccessful payments if(Regex.IsMatch(responseContent, Regex.Escape(identifier)+@";AS[1234]\d\d")) { return false; } throw new VerificationProviderException("Assist verification service returned unknown response.") { ResponseContent = responseContent }; }
/// <summary> /// Implement all the query logic in this method. /// </summary> /// <remarks> /// The cancellationToken must be checked when it is safe to cancel the /// operation. The blocking logic between two check points for cancellationToken /// should run as quick as possible. The logic will still be aborted if it takes too /// long after cancellationToken is canceled but no cancellation work is actually performed. /// The cancellation work can be simply return from the method or throw an OperationCanceledException. /// </remarks> /// <param name="cancellationToken">The cancellationToken to be checked.</param> /// <returns>Queried result</returns> protected override TaskQuickStatus QueryStatus(System.Threading.CancellationToken cancellationToken) { int count; for (count = 0; count < COUNT; count++) { // Check cancellationToken for the canceled state. cancellationToken.ThrowIfCancellationRequested(); // TODO: do real work, keep it as quick as possible. // Here, simply uses a timed wait to make it look like working on something. cancellationToken.WaitHandle.WaitOne(WAIT_TIMEOUT); } // Check the cancellationToken again cancellationToken.ThrowIfCancellationRequested(); return new TaskQuickStatus() { Mark = count.ToString(CultureInfo.CurrentCulture), StatusTips = String.Empty }; }
public async Task Excute(Command[] commands,System.Threading.CancellationToken token) { try { foreach (var command in commands) { token.ThrowIfCancellationRequested(); switch(command.Verb) { case Verb.Back: Back(); Straight(); break; case Verb.BackLeft: Back(); Left(); break; case Verb.BackRight: Back(); Right(); break; case Verb.Fowerd: Fowerd(); Straight(); break; case Verb.FowerdLeft: Fowerd(); Left(); break; case Verb.FowerdRight: Fowerd(); Right(); break; case Verb.Stop: Stop(); Straight(); break; } await Task.Delay(command.Time * 1000, token); } }catch(OperationCanceledException) { Console.WriteLine("Cancel"); } finally { Stop(); Straight(); } }
private void StartRegularDataCheck(System.Threading.CancellationToken cancellationToken) { Task.Run(async () => { var sotonmet = new SouthamptonVTSDataSource(SouthamptonVTSStation.Dockhead); var bramble = new SouthamptonVTSDataSource(SouthamptonVTSStation.Bramble); while (!cancellationToken.IsCancellationRequested) { var sotonRecord = sotonmet.GetLatestDataPoint(); var brambleRecord = bramble.GetLatestDataPoint(); await Task.Delay(60000).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); }, cancellationToken); }
public static System.Collections.Generic.IEnumerable<TypeDefinition> FindDerivedTypes(TypeDefinition type, ModuleDefinition[] assemblies, System.Threading.CancellationToken cancellationToken) { foreach (ModuleDefinition module in assemblies) { foreach (TypeDefinition td in ICSharpCode.NRefactory.Utils.TreeTraversal.PreOrder(module.Types, t => t.NestedTypes)) { cancellationToken.ThrowIfCancellationRequested(); if (type.IsInterface && td.HasInterfaces) { foreach (TypeReference typeRef in td.Interfaces) { if (IsSameType(typeRef, type)) yield return td; } } else if (!type.IsInterface && td.BaseType != null && IsSameType(td.BaseType, type)) { yield return td; } } } }
/// <summary> /// comingsoonでも止まるように変更した! /// </summary> /// <param name="live_id"></param> /// <param name="cc"></param> /// <param name="progress"></param> /// <param name="token"></param> /// <returns></returns> private async Task<Response<getplayerstatus_new>> GetSeatLoopTest(string live_id, System.Net.CookieContainer cc, IProgress<StringReport> progress, System.Threading.CancellationToken token, bool logging) { var report = new StringReport(); int loopCounter = 0; Response<getplayerstatus_new> response; do { //座席が取れた場合と座席を取るのが不可能な場合に結果を戻す。それ以外の場合には経過をReportして継続する。 token.ThrowIfCancellationRequested(); loopCounter++; response = await Api.GetPlayerStatus_new(live_id, cc, logging); if (response.status == status.ok) { return response.GetResponse(); } else { var code = response.GetError().code; switch (code) { case errorcode.closed: case errorcode.notfound: case errorcode.notlogin: case errorcode.require_community_member: case errorcode.deletedbyuser: //注意!! case errorcode.comingsoon: case errorcode.noauth: return response; default: break; } report.Message = string.Format("{0} {1, 4}回目", code, loopCounter); progress.Report(report); } } while (true); }
/// <summary> /// Waits for a shout request message to arrive in the Pub/Sub /// subscription. Converts the text to uppercase and posts the results /// back to the website. /// </summary> /// <returns> /// The number of messages pulled from the subscription, /// or -1 if an expected error occurred. /// </returns> public int ShoutOrThrow(System.Threading.CancellationToken cancellationToken) { // Pull a shout request message from the subscription. string subscriptionPath = MakeSubscriptionPath(_init.SubscriptionName); WriteLog("Pulling shout request messages from " + subscriptionPath + "...", TraceEventType.Verbose); var pullRequest = _init.PubsubService.Projects.Subscriptions.Pull( new PullRequest() { MaxMessages = 1, ReturnImmediately = false }, subscriptionPath).ExecuteAsync(); Task.WaitAny(new Task[] { pullRequest }, cancellationToken); var pullResponse = pullRequest.Result; int messageCount = pullResponse.ReceivedMessages == null ? 0 : pullResponse.ReceivedMessages.Count; WriteLog("Received " + messageCount + " messages.", TraceEventType.Information); if (messageCount < 1) return 0; // Nothing pulled. Nothing to do. // Examine the received message. var shoutRequestMessage = pullResponse.ReceivedMessages[0]; var attributes = shoutRequestMessage.Message.Attributes; string postStatusUrl; string postStatusToken; DateTime requestDeadline; try { postStatusUrl = attributes["postStatusUrl"]; postStatusToken = attributes["postStatusToken"]; long unixDeadline = Convert.ToInt64(attributes["deadline"]); requestDeadline = FromUnixTime(unixDeadline); } catch (Exception e) { WriteLog("Bad shout request message attributes.\n" + e.ToString(), TraceEventType.Warning); Acknowledge(shoutRequestMessage.AckId); return -1; } // Tell the world we are shouting this request. PublishStatus(postStatusUrl, postStatusToken, "shouting"); WriteLog("Shouting " + postStatusUrl, TraceEventType.Verbose); try { // Decode the payload, the string we want to shout. byte[] data = Convert.FromBase64String(shoutRequestMessage.Message.Data); string decodedString = Encoding.UTF8.GetString(data); // Watch the clock and cancellation token as we work. We need to extend the // ack deadline if the request takes a while. var tenSeconds = TimeSpan.FromSeconds(10); DateTime ackDeadline = DateTime.UtcNow + tenSeconds; ThrowIfAborted throwIfAborted = () => { cancellationToken.ThrowIfCancellationRequested(); var now = DateTime.UtcNow; if (requestDeadline < now) throw new FatalException("Request timed out."); if (ackDeadline < now) { // Tell the subscription we need more time: WriteLog("Need more time...", TraceEventType.Verbose); _init.PubsubService.Projects.Subscriptions.ModifyAckDeadline( new ModifyAckDeadlineRequest { AckIds = new string[] { shoutRequestMessage.AckId }, AckDeadlineSeconds = 15, }, MakeSubscriptionPath(_init.SubscriptionName)).Execute(); ackDeadline = now + tenSeconds; } }; // Shout it. string upperText = ShoutString(decodedString, throwIfAborted); // Publish the result. PublishStatus(postStatusUrl, postStatusToken, "success", upperText); Acknowledge(shoutRequestMessage.AckId); return 1; } catch (OperationCanceledException) { return 1; // Service stopped. Nothing to report. } catch (FatalException e) { WriteLog("Fatal exception while shouting:\n" + e.Message, TraceEventType.Error); Acknowledge(shoutRequestMessage.AckId); PublishStatus(postStatusUrl, postStatusToken, "fatal", e.Message); return -1; } catch (Exception e) { // Something went wrong while shouting. Report the error. WriteLog("Exception while shouting:\n" + e.Message, TraceEventType.Error); PublishStatus(postStatusUrl, postStatusToken, "error", e.Message); return -1; } }
public Task<Position> GetPositionAsync(int timeout, System.Threading.CancellationToken cancelToken, bool includeHeading) { var t = GetPositionAsync(timeout, includeHeading); while (t.Status == TaskStatus.Running) { cancelToken.ThrowIfCancellationRequested(); } return t; }
public async Task<Position> GetPositionAsync(System.Threading.CancellationToken cancelToken) { var t = locator.GetGeopositionAsync().AsTask(); while (t.Status == TaskStatus.Running) { cancelToken.ThrowIfCancellationRequested(); } var position = await t; return position.Coordinate.GetPosition(); }
/// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> /// <param name="append">Whether or not to append to the file if it exists</param> /// <param name="cancellationToken">Cancellation token which can be used to cancel this operation.</param> public async System.Threading.Tasks.Task WriteResponseStreamToFileAsync(string filePath, bool append, System.Threading.CancellationToken cancellationToken) { // Make sure the directory exists to write too. FileInfo fi = new FileInfo(filePath); Directory.CreateDirectory(fi.DirectoryName); Stream downloadStream; if (append && File.Exists(filePath)) downloadStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, S3Constants.DefaultBufferSize); else downloadStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, S3Constants.DefaultBufferSize); try { long current = 0; #if CORECLR Stream stream = this.ResponseStream; #else Stream stream = new BufferedStream(this.ResponseStream); #endif byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length) .ConfigureAwait(continueOnCapturedContext: false)) > 0) { cancellationToken.ThrowIfCancellationRequested(); await downloadStream.WriteAsync(buffer, 0, bytesRead) .ConfigureAwait(continueOnCapturedContext: false); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval || current == this.ContentLength) { this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); } finally { downloadStream.Dispose(); } }