Synchronize() hangs up the thread

血红的双手。 提交于 2019-12-05 08:17:19
Zoë Peterson

When you call TThread.Synchronize the thread and method pointer are added to a global SyncList: TList in Classes.pas. In the main exe's TApplication.Idle routine calls CheckSynchronize, which checks the SyncList, but it's going to check the version in the exe instead of the one in the DLL. End result, your synchronized methods are never called.

The easiest fix would be to switch from DLLs to packages, which would eliminate the duplicate SyncList.

Another approach would be to override the exe's Application.OnIdle callback, and call your DLL's CheckSynchronize manually. You would need some help from the application for that though, since your DLL will have an Application object too, and that one won't work.

It's a bad idea to use Synchronize, because it tends to lead to race conditions like this. I don't know what's going on specifically in your code--it's hard to tell without seeing any code--but this sort of issue is pretty common actually.

Inter-thread communication is better done with a queue. If you've got the latest version, Delphi XE, there's a TThreadedQueue<T> class in Generics.Collections that's ideal for this sort of thing. Pass 0 to the PopTimeout param in the constructor, have your camera threads push images, and have your main thread poll the queues with the third PopItem overload, like so:

var
  CurrentItem: TImage;
begin
  if ThreadQueue.PopItem(CurrentItem) = wrSignaled then
    UpdateImage(CurrentItem); //or however you do it
end;

(If there's nothing in the queue, PopItem will return wrTimeout instead.)

If you don't have Delphi XE, you'll need to build your own threadsafe queue, or find one from a third party source, such as Primoz Gabrielcic's OmniThreadLibrary.

Triplodox

I found two ways to solve Synchronize() hanging up the thread (in Delphi 7):

  1. Place a TTimer on the Dll form and onTimer event call CheckSynchronize;

procedure TPluginForm.Timer1Timer(Sender: TObject); begin CheckSynchronize; end;

  1. Add this module to uses section of the Dll form
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!