Is it dangerous to use synchronize in a non-VCL application?

后端 未结 3 892
你的背包
你的背包 2021-01-01 23:20

If Delphi code was written with synchronize to serialize access to the main VCL thread, but this code then is used in a non-VCL application, will it synchronize with the mai

相关标签:
3条回答
  • 2021-01-01 23:35

    Since you are putting the Delphi code in a library for other apps to use, I would not advise using Synchronize() at all, since you thread has no concept of what is going on outside of itself. A better choice is to have the thread expose a callback event that the thread can call in its own context when needed, and then let the app provide a callback function handler that decides the best way to synchronize with the app's main thread as needed.

    0 讨论(0)
  • 2021-01-01 23:51

    Is it dangerous to use synchronize in a non-VCL application?

    Yes it is dangerous. If your main thread is not calling CheckSynchronize then Synchronize will result in deadlock.

    Let's assume

    • it is a non-VCL application which has a main thread which executes in an endless loop (or until terminated)
    • the main thread does not call CheckSynchronize directly or in a WakeMainThread handler
    • a secondary thread runs and executes Synchronize(SomeMethod) like in the example above

    Will the thread hang on the Synchronize(SomeMethod) line?

    The call to Synchronize will block the background thread until the main thread calls CheckSynchronize. So, if the main thread never calls CheckSynchronize, the background thread will block indefinitely.

    The following program illustrates this:

    program TheBigSleep;
    
    {$APPTYPE CONSOLE}
    
    uses
      SysUtils, Classes, Windows;
    
    type
      TMyThread = class(TThread)
      protected
        procedure Execute; override;
      end;
    
    procedure TMyThread.Execute;
    begin
      Synchronize(SysUtils.Beep);
    end;
    
    begin
      with TMyThread.Create do
        WaitForSingleObject(Handle, INFINITE);
        //don't call WaitFor since that, in turn, calls CheckSynchronize
    end.
    
    0 讨论(0)
  • 2021-01-01 23:53

    TThread provides facilities for non-VCL programs to check the synchronization queue, so they can continue to use multithreaded libraries that expect to synchronize their methods. This is described in the documentation for CheckSynchronize. Remember that it's the application's job to check the queue, not your library's.

    As long as the application honors its part of the contract, your use of Synchronize should be fine. If it doesn't, though, then your program will not work correctly, but I don't know what exact symptoms to expect. Hanging certainly sounds plausible.

    0 讨论(0)
提交回复
热议问题