I
I
Igor2019-09-17 12:20:53
Delphi
Igor, 2019-09-17 12:20:53

Delphi Thread try finally?

Colleagues, good afternoon!
I simplified the code as much as possible for understanding.
Some miracles happen.
The meaning is quite simple.
In a loop, we turn to the server.
Sorry, we're done.
But at some point something happens and it just doesn't work. And the cycle stays forever locked
ThreadCounter := ThreadCounter - 1;

while ThreadCounter >= 2 do
    begin
      Application.ProcessMessages;
      Sleep(100);
    end;

while KWEnum.MoveNext do
  begin

    Thread := TCollectUrlThread.CreateAnonymousThread(
      procedure
      var
        Content: string;
        uri: TURI;
        i: integer;
        KRUrl: TKRUrl;
        KRUrls: TArray<TKRUrl>;
        KRUrlsCollection: TArray<TKRUrl>;
        mce: TMatchCollectionEnumerator;

        this: TCollectUrlThread;
      begin
        this := TThread.Current as TCollectUrlThread;
        try
          // Здесь формирую параметры
          try
            // здесь HTTP запрос

            try
               // здесь парсинг с помощью регулярок
            except
              // могут быть исключения при парсинге
              on E: Exception do
                raise Exception.Create(E.Message);
            end;

            if TRegEx.IsMatch(Content, '\/search\/\?.*?(")', [roSingleLine]) then
            begin
              mce := TRegEx.Matches(Content, '\/search\/\?.*?(")', [roSingleLine]).GetEnumerator;

              while mce.MoveNext do
              begin
                try
                 // Дополнительный запрос по HTTP

                 // Дополнительный парсинг с помощью регулярок

                except
                  on E: Exception do
                    raise Exception.Create(E.Message);
                end;
              end;
            end;

          except
            // Здесь фиксирую общие ошибки.
          end;

          // пишу в базу с помощью FireDAC

        finally
          // ОЧЕНЬ ВАЖНО!
          // ОБЯЗАТЕЛЬНЫЙ ДЕКРИМЕНТ
          ThreadCounter := ThreadCounter - 1; 
        end;
      end);

    // Создаю новый поток
    Inc(ThreadCounter);
    Thread.keyword := KWEnum.Current;
    Thread.project_id := ProjectId;
    Thread.Resume;

    // Ограничитель потоков
    while ThreadCounter >= 2 do
    begin
      Application.ProcessMessages;
      Sleep(100);
    end;
  end;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question