How to terminate anonymous threads in Delphi on application close?

前端 未结 3 456
無奈伤痛
無奈伤痛 2021-01-02 09:50

I have a Delphi application which spawns 6 anonymous threads upon some TTimer.OnTimer event.

If I close the application from the X button in titlebar Access Violatio

相关标签:
3条回答
  • 2021-01-02 10:38

    To avoid errors using CreateAnonymousThread just set FreeOnTerminate to False before starting it.

    This way you can work with the thread as you usually do without any workaround.

    You can read the documentation that says that CreateAnonymousThread automatically sets FreeOnTerminate to True and this is what is causing the errors when you reference the thread.

    0 讨论(0)
  • 2021-01-02 10:41

    If you want to maintain and exert control over a thread's lifetimes then it must have FreeOnTerminate set to False. Otherwise it is an error to refer to the thread after it has started executing. That's because once it starts executing, you've no ready way to know whether or not it has been freed.

    The call to CreateAnonymousThread creates a thread with FreeOnTerminate set to True.

    The thread is also marked as FreeOnTerminate, so you should not touch the returned instance after calling Start.

    And so, but default, you are in no position to exert control over the thread's lifetime. However, you could set FreeOnTerminate to False immediately before calling Start. Like this:

    MyThread := TThread.CreateAnonymousThread(MyProc);
    MyThread.FreeOnTerminate := False;
    MyThread.Start;
    

    However, I'm not sure I would do that. The design of CreateAnonymousThread is that the thread is automatically freed upon termination. I think I personally would either follow the intended design, or derive my own TThread descendent.

    0 讨论(0)
  • 2021-01-02 10:48

    Make your threads watch for some kind of notification from the outside. This could be an event that gets signaled, a message sent to a window owned by the thread, a command sent over a socket that your thread listens to, or whatever other form of communication you find.

    If you determine that this problem is because your threads are so-called "anonymous" threads, then a simple workaround is for you to make them be non-anonymous threads. Put the body of the anonymous function into the Execute method, and pass any captured variables to the thread class via its constructor.

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