2
votes

So, my goal is start a function in another thread. Also i need access to other vcl components from new thread. Here is my code so far:

procedure TForm1.StartButtonClick(Sender: TObject);
var
thread1: integer;
id1: longword;
begin
   thread1 := beginthread(nil,0,Addr(Tform1.fetchingdata),nil,0,id1);
    closehandle(thread1);
end;

procedure TForm1.FetchingData;
var
  ...
begin
  Idhttp1.IOHandler := IdSSLIOHandlerSocketOpenSSL1;   //<- error
  idhttp1.Request.ContentType := 'application/x-www-form-urlencoded';

my program hangs and i get error: Exception EAccessViolation in module my.exe at 00154E53. Access violation at address 00554E53 in module 'my.exe'. Read of address 00000398.

Thanks in advance.

3

3 Answers

9
votes

The cause of the AV is that you pass the address of a TForm method to a function that expects a TThreadFunc (see the documentation of System.BeginThread()). Using Addr() like this is a good way to keep the compiler from pointing out your bugs.

What you would need to do instead is to write a wrapper function that has the correct signature, pass the form instance as the parameter, and call the method on the form from that function.

But don't go there, either write your code as a descendant of TThread, or (preferably) use a higher level wrapper like AsyncCalls or the Omni Thread Library. And make sure that you don't access VCL components in the main thread, create and free those that you need in your worker thread.

6
votes

The VCL (Gui components) is only to be accessed from the main thread. Other threads need the main thread to access the VCL.

0
votes

You could try the same thing with a regular TThread if you're using Delphi or Lazarus.

    type
          TSeparateThread = class(TThread)
            private
            protected
            public
              constructor Create(IfSuspend: Boolean);
              proceedure Execute; override;
            // variables to fill go here
            // s : String;
            // i : Integer;
            // etc...
          end;

        constructor TSeparateThread.Create(IfSuspend: Boolean);
        begin
          inherited Create(IfSuspend);    
        end;

        procedure TSeparateThread.Execute;
        begin

  // This is where you will do things with those variables and then pass them back.

        YourMainUnitOrForm.PublicVariableOf := s[i];

  // passes position 0 of s to PublicVariableOf in your Main Thread

        end;

Calling the new Thread is done as follows:

with TSeparateThread.Create(true) do
  begin

  // This is where you fill those variables passed to the new Thread
          s := 'from main program';
          i := 0;
  // etc...

    Resume; 

  //Will Start the Execution of the New Thread with the variables filled.

  end;