OnTerminate应该同步吗?

时间:2017-01-27 12:09:48

标签: delphi

创建线程时,

SELECT CAST(value AS int) FROM STRING_SPLIT(@ReportId, ' ') 将名为TThread的Thread函数传递给ThreadProc。 这是CreateThread使用的ThreadProc

TThread

...这是function ThreadProc(Thread: TThread): Integer; var FreeThread: Boolean; begin TThread.FCurrentThread := Thread; {$IF Defined(MACOS)} if Thread.FSuspended then pthread_mutex_lock(Thread.FCreateSuspendedMutex); {$ELSEIF Defined(LINUX)} if Thread.FSuspended then sem_wait(Thread.FCreateSuspendedSem); {$ENDIF LINUX} try if not Thread.Terminated then try Thread.Execute; except Thread.FFatalException := AcquireExceptionObject; end; finally Result := Thread.FReturnValue; FreeThread := Thread.FFreeOnTerminate; Thread.DoTerminate; Thread.FFinished := True; SignalSyncEvent; if FreeThread then Thread.Free; {$IF Defined(MSWINDOWS)} EndThread(Result); {$ELSEIF Defined(POSIX)} // Directly call pthread_exit since EndThread will detach the thread causing // the pthread_join in TThread.WaitFor to fail. Also, make sure the EndThreadProc // is called just like EndThread would do. EndThreadProc should not return // and call pthread_exit itself. if Assigned(EndThreadProc) then EndThreadProc(Result); pthread_exit(Result); {$ENDIF POSIX} end; end; 中的代码:

Thread.DoTerminate

所以我的问题是; procedure TThread.CallOnTerminate; begin if Assigned(FOnTerminate) then FOnTerminate(Self); end; procedure TThread.DoTerminate; begin if Assigned(FOnTerminate) then Synchronize(CallOnTerminate); end; 应该同步吗?为什么同步是默认行为?是不是应由开发人员决定?

我在问,因为我无法弄清楚为什么它会被同步,以及在大多数情况下这种行为是否最好。

1 个答案:

答案 0 :(得分:6)

为方便起见,TThread类安排在主线程上执行OnTerminate事件处理程序。它最常用于允许主线程响应完成的线程。在这种情况下,代码在主线程上执行最有用。例如,通常清除对线程的引用,或者在线程终止时执行UI任务。通过在主线程上执行事件处理程序,这些任务将在正确的线程上自动执行。

如果您希望此时在线程中执行工作,您可以覆盖DoTerminate并将工作放在那里。

换句话说,你仍然可以选择。如果您希望代码在主线程上运行,请将其放在OnTerminate事件处理程序中。如果您希望代码在线程中运行,请覆盖DoTerminate