Sup*_*Bug 1 delphi multithreading android firemonkey
我尝试使用来自此多线程的方法使用 delphi firemonkey 为 android 平台创建多线程
它不起作用,有没有办法创建这样的工作线程?
谢谢。
您可以使用并行编程库,这里使用创建线程的任务是一个快速示例
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;
Run Code Online (Sandbox Code Playgroud)
添加:
如果你想在你的评论中想要 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;
Run Code Online (Sandbox Code Playgroud)