在 Delphi 10.1 Berlin 中,我想添加停止响应式 TParallel 的可能性。
如果您将所有
更新:这被报告为一个错误,在 Delphi 10.2.3 Tokyo 中仍未修复。 https://quality.embarcadero.com/browse/RSP-11267
要解决这个特定问题,您需要在
当一项任务开始时,UI 应该阻止任何开始新计算的尝试,直到前者准备好/取消。
现在,有一种安全的方法可以知道任务何时完成/停止或取消。
完成后,删除
如果
一个例子:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | TCalculationProject = class(TObject) private Task: ITask; public List: TList<Real>; procedure CancelButtonClicked; function CalculateListItem(const AIndex: Integer): Real; procedure CalculateList(NotifyCompleted: TNotifyEvent); Destructor Destroy; Override; end; procedure TCalculationProject.CancelButtonClicked; begin if Assigned(Task) then begin Task.Cancel; end; end; destructor TCalculationProject.Destroy; begin List.Free; inherited; end; function TCalculationProject.CalculateListItem(const AIndex: Integer): Real; begin //a function which takes a lot of calculation time //however in this example we simulate the calculation time and //use a simple alogorithm to verify the list afterwards Sleep(30); Result:=10*AIndex; end; procedure TCalculationProject.CalculateList(NotifyCompleted: TNotifyEvent); begin if not Assigned(List) then List := TList<Real>.Create; List.Clear; Task:= TTask.Run( procedure var LoopResult : TParallel.TLoopResult; Lock : TCriticalSection; begin Lock:= TCriticalSection.Create; try LoopResult:= TParallel.&For(0, 1000-1, procedure(AIndex: Integer; LoopState: TParallel.TLoopState) var Res: Real; begin if (Task.Status=TTaskStatus.Canceled) and not(LoopState.Stopped) then begin LoopState.Stop; end; if LoopState.Stopped then begin Exit; end; Res:= CalculateListItem(AIndex); Lock.Enter; try List.Add(Res); finally Lock.Leave; end; end); finally Lock.Free; end; if (Task.Status = TTaskStatus.Canceled) then TThread.Synchronize(TThread.Current, procedure begin List.Clear; end) else if LoopResult.Completed then TThread.Synchronize(TThread.Current, procedure begin SortList; ShowList; end); // Notify the main thread that the task is ended TThread.Synchronize(nil, // Or TThread.Queue procedure begin NotifyCompleted(Self); end); end ); end; |
以及 UI 调用:
2 3 4 5 6 7 8 9 10 | begin StartCalc.Enabled := false; CalcObj.CalculateList(TaskCompleted); end; procedure TMyForm.TaskCompleted(Sender: TObject); begin StartCalc.Enabled := true; end; |
在评论中,用户希望在一个操作中触发取消和新任务而不被阻止。
为了解决这个问题,设置一个标志为真,在任务上调用取消。当调用
取消在 System.Threading 中被破坏。请参阅 https://quality.embarcadero.com/browse/RSP-11267
以下工作通过使用另一种机制来通知线程停止 (StopRunning)。注意 LoopState.Break 和 LoopState.ShouldExit 的使用。还要注意使用队列而不是同步。这允许我们在主线程上等待任务而不会阻塞。
要使用代码,您需要一个带有 ListBox1 和两个按钮 btnStart 和 btnCancel 的表单。
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | TForm1 = class(TForm) btnStart: TButton; btnCancel: TButton; ListBox1: TListBox; procedure btnStartClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private declarations } private Task: ITask; public { Public declarations } List: TList<Double>; StopRunning : Boolean; function CalculateListItem(const AIndex: Integer): Real; procedure CalculateList; procedure ShowList; end; var Form1: TForm1; implementation uses System.SyncObjs; {$R *.dfm} function TForm1.CalculateListItem(const AIndex: Integer): Real; begin //a function which takes a lot of calculation time //however in this example we simulate the calculation time and //use a simple alogorithm to verify the list afterwards Sleep(30); Result:=10*AIndex; end; procedure TForm1.FormCreate(Sender: TObject); begin List := TList<Double>.Create; end; procedure TForm1.FormDestroy(Sender: TObject); begin List.Free; end; procedure TForm1.ShowList; Var R : Double; begin for R in List do ListBox1.Items.Add(R.ToString); end; procedure TForm1.CalculateList; Var R : Real; begin List.Clear; if Assigned(Task) then begin Task.Cancel; end; StopRunning := False; Task:=TTask.Run( procedure var LoopResult: TParallel.TLoopResult; Lock: TCriticalSection; begin Lock:=TCriticalSection.Create; try LoopResult:=TParallel.For(0, 1000-1, procedure(AIndex: Integer; LoopState: TParallel.TLoopState) var Res: Double; begin if StopRunning then begin LoopState.Break; Exit; end; if LoopState.ShouldExit then Exit; Res:=CalculateListItem(AIndex); Lock.Enter; try List.Add(Res); finally Lock.Leave; end; end ); finally Lock.Free; end; if LoopResult.Completed then TThread.Queue(TThread.Current, procedure begin List.Sort; ShowList; end ) else TThread.Queue(TThread.Current, procedure begin List.Clear; ListBox1.Items.Add('Cancelled') end ); end ); end; procedure TForm1.btnCancelClick(Sender: TObject); begin StopRunning := True; Task.Wait; end; procedure TForm1.btnStartClick(Sender: TObject); begin ListBox1.Clear; CalculateList; end; |
在@pyscripters 回答的基础上,我尝试将功能封装在一个类中,并从 UI 调用该类的功能。
最后的提示是将 CheckSynchronize 添加到 Shutdown 方法中。
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | interface uses System.Classes, System.Generics.Collections, System.Threading; type TNotifyTaskEvent = procedure(Sender: TObject; AMessage: string) of object; TCalc2 = class private FTask : ITask; FOnNotifyTaskEvent: TNotifyTaskEvent; FCancelTask : Boolean; function CalculateListItem(const AIndex: Integer): Real; procedure CalculateList; procedure DoNotify(AMessage: string); public List: TList<Double>; constructor Create; destructor Destroy; override; procedure Start; procedure Stop; property OnNotifyTaskEvent: TNotifyTaskEvent read FOnNotifyTaskEvent write FOnNotifyTaskEvent; end; implementation uses System.SysUtils, System.SyncObjs; constructor TCalc2.Create; begin List := TList<Double>.Create; end; destructor TCalc2.Destroy; begin FOnNotifyTaskEvent := Nil; Stop; CheckSynchronize; FTask := Nil; List.Free; inherited; end; procedure TCalc2.DoNotify(AMessage: string); begin if Assigned(FOnNotifyTaskEvent) then begin if Assigned(FTask) then AMessage := Format('%4d: %-40s Entries=%3d', [FTask.Id, AMessage, List.Count]) else AMessage := Format('%4d: %-40s Entries=%3d', [0, AMessage, List.Count]); FOnNotifyTaskEvent(Self, AMessage); end; end; function TCalc2.CalculateListItem(const AIndex: Integer): Real; begin //a function which takes a lot of calculation time //however in this example we simulate the calculation time and //use a simple alogorithm to verify the list afterwards Sleep(30); Result := 10 * AIndex; end; procedure TCalc2.CalculateList; begin List.Clear; if Assigned(FTask) then begin FTask.Cancel; end; FCancelTask := False; FTask := TTask.Run( procedure var LoopResult: TParallel.TLoopResult; Lock: TCriticalSection; begin // TThread.Queue(TThread.Current, // procedure // begin // DoNotify('Started'); // end // ); Lock := TCriticalSection.Create; try LoopResult := TParallel.For(0, 500 - 1, procedure(AIndex: Integer; LoopState: TParallel.TLoopState) var Res: Double; begin if FCancelTask then begin LoopState.Break; Exit; end; if LoopState.ShouldExit then Exit; Res := CalculateListItem(AIndex); Lock.Enter; try List.Add(Res); finally Lock.Leave; end; end ); finally Lock.Free; end; if LoopResult.Completed then TThread.Queue(TThread.Current, procedure begin DoNotify('Completed'); end ) else TThread.Queue(TThread.Current, procedure begin DoNotify('Canceled'); end ); end ); end; procedure TCalc2.Start; begin CalculateList; end; procedure TCalc2.Stop; begin FCancelTask := True; if Assigned(FTask) then FTask.Wait; end; end. |
来自 UI 的调用如下所示:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | begin FCalc2 := TCalc2.Create; FCalc2.OnNotifyTaskEvent := CalcCompleted; end; procedure TForm5.FormDestroy(Sender: TObject); begin FCalc2.Free; end; procedure TForm5.btnCalcCancelClick(Sender: TObject); begin FCalc2.Stop; end; procedure TForm5.btnCalcRunClick(Sender: TObject); begin CalcRun; end; procedure TForm5.btnRunAnotherClick(Sender: TObject); begin CalcRun; end; procedure TForm5.CalcCompleted(Sender: TObject; Status: string); begin memStatus.Lines.Add(Status); btnCalcRun.Enabled := true; end; procedure TForm5.CalcRun; begin btnCalcRun.Enabled := false; memStatus.Lines.Add('Started'); FCalc2.Stop; FCalc2.Start; end; |
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解