【发布时间】:2016-02-06 19:55:48
【问题描述】:
【问题讨论】:
-
究竟是什么不起作用?也许看看 TTask docwiki.embarcadero.com/RADStudio/XE7/en/…
标签: android multithreading delphi firemonkey
【问题讨论】:
标签: android multithreading delphi firemonkey
您可以使用并行编程库,这里使用创建线程的任务是一个快速示例
uses: System.Threading
var
Mythreadtask : ITask;
procedure createthreads;
begin
if Assigned(Mythreadtask) then
begin
if Mythreadtask.Status = TTaskStatus.Running then
begin
//If it is already running don't start it again
Exit;
end;
end;
Mythreadtask := TTask.Create (procedure ()
var s : String //Create Thread var here
begin
//Do all logic in here
//If you need to do any UI related modifications
TThread.Synchronize(TThread.CurrentThread,procedure()
begin
//Remeber to wrap them inside a Syncronize
end);
end);
// Ensure that objects hold no references to other objects so that they can be freed, to avoid memory leaks.
end;
添加:
如果你想在你的评论中点赞想要 5 个工作线程,你可以使用一系列任务,这是从并行编程库文档中提取的
procedure createthreads;
var
tasks: array of ITask; //Declare your dynamic array of ITask
value: Integer;
begin
Setlength (tasks ,2); // Set the size of the Array (How many threads you want to use in your case this would be 5)
value := 0;
//This the 1st thread because it is the thread located in position 1 of the array of tasks
tasks[0] := TTask.Create (procedure ()
begin
sleep (3000); // 3 seconds
TInterlocked.Add (value, 3000);
end);
tasks[0].Start;// until .Start is called your task is not executed
// this starts the thread that is located in the position [0] of tasks
//And this is the 2nd thread
tasks[1] := TTask.Create (procedure ()
begin
sleep (5000); // 5 seconds
TInterlocked.Add (value, 5000);
end);
tasks[1].Start;// and the second thread is started
TTask.WaitForAll(tasks); {This will have the mainthread wait for all the
{threads of tasks to finish before moving making sure that when the
showmessage All done is displayed all the threads are done}
ShowMessage ('All done: ' + value.ToString);
end;
【讨论】: