Is it safe to send an event from the main thread to the worker thread and wait for it?

I am working on such an action queue thread, and I would like to wait for a specific action to complete. I would like to create an action in the main thread, and then pass it to the function of the queue thread (until the end of the queue) and wait for this action to be completed. Therefore, I need to distinguish the action that I just requested and is waiting for it.

I have the following (pseudo) code and I would like to know

  • Does it work with a stream of Windows event objects?
  • if so, will this concept be effective?

type
  TMyThread = class(TThread);
  private
    FEvent: THandle;
  protected
    procedure Execute; override;
  public
    procedure DoSomething(const AEvent: THandle);
  end;

procedure TMyThread.Execute;
begin
  //  is it working with events thread safe ?
  SetEvent(FEvent);
  //  the thread will continue, so I can't use WaitFor
  //  but it won't set this specific FEvent handle again
  //  I'm working on such kind of an action queue, so once the action with ID,
  //  here represented by the FEvent will be processed, it removed from 
  //  the action queue
end;

procedure TMyThread.DoSomething(const AEvent: THandle);
begin
  FEvent := AEvent;
end;

//  here roughly what I want to do

procedure TForm1.Button1Click(Sender: TObject);
var
  OnceUsedEvent: THandle;
begin
  //  the thread is already running and it instantiated in MyThread
  //  here I'm creating the event for the single request I need to be performed
  //  by the worker thread
  OnceUsedEvent := CreateEvent(nil, True, False, nil);
  try 
  //  here I'm passing the event handle to the worker thread (like a kind of
  //  a request ID)
    MyThread.DoSomething(OnceUsedEvent);
  //  and here I want to wait for 10 seconds (and also interrupt this waiting 
  //  when the user closes the application if possible ?) for the thread if
  //  performs my request
    WaitForSingleObject(OnceUsedEvent, 10000);
  finally
  //  close the event handle
    CloseHandle(OnceUsedEvent);
  end;
  //  and continue with something else
end;

Thank!

+5
source share
2 answers

, . , CreateEvent, . , :)

+4

GUI. , , , sleep(), DoEvents .

, , - , API PostMessage().

+3

All Articles