简体   繁体   English

TTimer.OnTimer会导致工作线程与主线程同步吗?

[英]Does TTimer.OnTimer causes a worker thread to synchronize with a main thread?

I have to work with legacy code. 我必须使用遗留代码。 This code has a TTimer created in a main thread. 这段代码在主线程中创建了一个TTimer In OnTimer event the timer is checking periodically a state of some data in the worker thread. OnTimer事件中,计时器会定期检查工作线程中某些数据的状态。

pseudocode: 伪代码:

procedure MainForm.OnTimer(Sender: TObject);
begin
  if WorkerThread.Data.State = full then
  begin
    WorkerThread.Free; //This freezes GUI.    
  end else
   //Do something else.
end;

The problem is that I want to do some background operation when the WorkerThread is terminating. 问题是我想在WorkerThread终止时执行一些后台操作。 To avoid synchronization I've overriden DoTerminate method. 为了避免同步,我重写了DoTerminate方法。 However in this particular case, this is not helping and my GUI becomes frozen until the DoTerminate finishes. 但是,在这种情况下,这DoTerminate并且我的GUI会冻结,直到DoTerminate完成为止。

Can I somehow avoid the freeze? 我可以以某种方式避免冻结吗?

Thanks. 谢谢。

There's not enough code here to say anything with any certainty. 这里没有足够的代码来说明任何事情。 However, calling Free on a thread results in a call to Terminate followed by a WaitFor . 但是,在线程上调用Free将导致对Terminate的调用,然后是WaitFor It's quite plausible that the wait is not returning which would be consistent with the frozen UI. 等待没有返回,这与冻结的UI一致,这是非常合理的。

This is truly backwards. 这确实是倒退。 In any decent threading scheme, your thread will be notifying your gui-thread about a condition like .Data.State = full. 在任何体面的线程方案中,您的线程将通知您的gui-thread有关.Data.State = full的条件。 You gui-thread or main-thread will then take appropriate action. 您的gui线程或主线程将采取适当的措施。 One thing i am certain about is that WorkerThread.Free must be wrong. 我确定的一件事是WorkerThread.Free一定是错的。 Trying to free a thread that's apparently blocked for whatever reason, is guaranteed to fail. 试图释放一个显然因任何原因被阻止的线程,保证会失败。 Thread.Terminate will also fail if the thread is blocked, so no help there either. 如果线程被阻塞,Thread.Terminate也会失败,所以也没有帮助。

Having a Timer monitor the status of a thread is never right. 让计时器监视线程的状态永远是不正确的。 I never use the words always and never, but... I'll repeat: Having a Timer monitor the status of a thread is never right. 我从不使用永远和永远的单词,但是......我将重复:使用Timer监视器线程的状态永远不对。 Never ever. 永远不能。 Don't even think about it. 甚至不用考虑。

  • turin 都灵

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM