Getting a Delphi TTimer to work with a multi-threading app

▼魔方 西西 提交于 2019-12-22 09:57:16

问题


I have an issue with a simple TTimer that's initiated and have its OnTimer event executed in the main app thread, the code looks like this:

procedure TForm1.DoSomeStuff();
begin
     OmniLock.Acquire;
     try
        Parallel.Pipeline.NumTasks(MaxThreads).Stage(StageProc).Run;

        if (MyTimer = nil) then
        begin
             MyTimer := TTimer.Create(nil);
             MyTimer.Interval := 60 * 1000;  // timer fired every 60 seconds
             MyTimer.OnTimer := MyTimerEvent;
             MyTimer.Enabled := True;
         end;
      finally
             OmniLock.Release;
      end;    // try/finally
 end;

Everthing work just fine when I execute the code in a simple project/demo, but in my app (which uses Omni Thread Library v3), the timer event is never fired

I'm pretty sure it's nothing, I just can't figure out what's wrong!

I triple checked: MyTimer is only assigned once in my code, its OnTimer event is correctly assigned, etc...

I'm using Delphi 2010

Anyone knows how to fix this?


回答1:


TTimer is a message based timer. Whatever thread context the TTimer is created in must have an active message loop in order for TTimer to process its WM_TIMER messages.

TTimer is not a thread-safe timer. In order to receive the WM_TIMER messages, it has to allocate an HWND window handle for itself. It does so using the VCL's AllocateHWnd() function, which is not thread-safe and must not be called from outside the context of the main thread.

If you need a thread-safe timer, either call CreateWindow() directly and pump/process the WM_TIMER messages directly, or else use a different timer mechanism, such as a threaded multimedia timer via timeSetEvent(), or even just a simple busy loop via Sleep() or WaitForSingleObject(). Without knowing what you are using the timer for, it is difficult to pin-point an alternative that suits your needs.



来源:https://stackoverflow.com/questions/10589749/getting-a-delphi-ttimer-to-work-with-a-multi-threading-app

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