Jump to content
hschmid67

Watch one task with another - restart if stopped

Recommended Posts

using OmniThreadLibrary I'd like to watch a task2 using another task1 to detect, if task2 is stopped or otherwise finished. The aim is to restart task2 if it stopped for any reason. Until now I use the following construct:

  Task1 := CreateTask(
    procedure(const mTask: IOmniTask)
    begin
      while not mTask.Terminated do
      begin
        Sleep(1000);
        // create Task2 and run it, if it is not running
        if Task2 = nil then
        begin
          Task2 := CreateTask(
            procedure(const mTask: IOmniTask)
            begin
              while not mTask.Terminated do
              begin
                Sleep(1000);
              end;
            end)
            .OnTerminated(procedure(const mTask: IOmniTaskControl)
              begin
                Task2 := nil;
              end);
          Task2.Run;
        end;
      end;
    end)
    .OnTerminated(
      procedure(const mTask: IOmniTaskControl)
      begin
        Task1 := nil;
      end);
  Task1.Run;

If I try to terminate the inner task2 with this code

Task2.Terminate(10000);

I get the following error:

Quote

TOmniEventMonitorPool.Release: Monitor is not allocated for thread xxx.

 

The same code work well with task1:

Task1.Terminate(10000);

Two questions:

  1. I do not understand, what goes wrong with this code and what the "monitoring"-error means.
  2. How can I get task1 to start task2 properly, and restart it, if task2 finished?

Thanks in advance

Share this post


Link to post

This looks like a bug in OTL. Can you please create a small, self-contained, compilable example so I can retest?

 

As a workaround, why do you need Task1 to monitor Task2? This should work equally well:

 

procedure RunTask;
begin
  Task2 := CreateTask(
            procedure(const mTask: IOmniTask)
            begin
              ...
            end)
            .OnTerminated(procedure(const mTask: IOmniTaskControl)
              begin
                Task2 := nil;
                RunTask;
              end);
  Task2.Run;
end;

 

Share this post


Link to post

Thanks for looking into my code. Attached is a selfcontained example.

Terminating Task1 first and then terminating Task2 I get this error of pic1.png.

Terminating Task2 first I get immediately the error of pic2.png.

 

Test2Tasks.zip

pic1.png

pic2.png

Share this post


Link to post

btw, if I call

 

Task2.stop();
Task2.WaitFor(10000);
Task2 := nil;

instead of

 

Task2.Terminate(10000);

everything works - without errormessage, but the OnTerminated-Handler is not called any more (that's why I assign nil to Task2 there)...

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×