Delphi - timer inside thread generates AV

前端 未结 6 1961
忘掉有多难
忘掉有多难 2020-12-07 23:56

I have the following thread code which executes correct first time. After that from time to time I get an AV on the Execute method of the thread, e.g

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 00:13

    First, in constructor TProcesses.Create(aGrid : TJvStringGrid); you have:

    FTimer.OnTimer := OverrideOnTerminate;
    FTimer.OnTimer := OverrideOnTimer;
    

    Here OverrideOnTerminate never fires. Probably you want to catch thread OnTerminate.

    Second, you create thread in running state inherited Create(false); so Execute is called automatically. When Execute is finished it calls DoTerminate and thread is destroyed.

    Next, when timer fire OnTimer you call multiple times Execute; Here Thread already may not exists. Timer is not freed, and you try to start a dead thread.

    You need to rewrite your code following some rules:

    1. Execute should run continuously. You may put thread to "sleep" using WaitForSingleObject/WaitForMultipleObjects. Take a look at MSDN help.
    2. These functions have Timeout parameter, so you don't need TTimer at all.

    [EDIT] I found some useful sample for you (sorry, it's not tested by me):

    procedure TProcesses.Execute;
    const  
     _SECOND = 10000000;  
    var  
     lBusy : LongInt;  
     hTimer : LongInt;  
     liWaitTime : LARGE_INTEGER;  
    begin  
      hTimer := CreateWaitableTimer(nil, True, 'WaitableTimer');
      liWaitTime.QuadPart := _SECOND * YOUR_NumberOfSeconds;
      SetWaitableTimer(hTimer, TLargeInteger(liWaitTime ), 0, nil, nil, False);  
      repeat  
        lBusy := MsgWaitForMultipleObjects(1, hTimer, False, INFINITE, QS_ALLINPUT);
        // CODE EXECUTED HERE EVERY YOUR_NumberOfSeconds
       Until lBusy = WAIT_OBJECT_0;  
       CloseHandle(hTimer);  
    end;  
    

    You need to slightly adjust this. Add one more object to wait for: an event created with CreateEvent function. When you need to instantly terminate thread just call SetEvent function.

提交回复
热议问题