Jump to content
alogrep

Printing in a threaded program

Recommended Posts

Hi. I have a program that creates a thread for each request. Some functions in the thread are involving printing to the standard Printer. If I do

 Printer.Canvas.lock;

Printer.BeginDoc

....

....

Printer.Enddoc;

Printer.Canvas.unlock;

Would it be thread safe?

Share this post


Link to post

How do you detect if the printer is in use or not? You're accessing one stateful device that's effectively a singleton so the access has to be serialized. If you insist on using threads, you could write a dedicated printer thread. 

 

 

Edited by A.M. Hoornweg

Share this post


Link to post
7 hours ago, A.M. Hoornweg said:

How do you detect if the printer is in use or not? You're accessing one stateful device that's effectively a singleton so the access has to be serialized. If you insist on using threads, you could write a dedicated printer thread. 

Yes, the Printer global TPrinter instance is a singleton and AFAIK it is not thread safe. However I can't see why it should be a problem for each thread to create their own TPrinter instance and use that to print. The print job context wrapped by TPrinter is not a singleton and the target print device does not necessarily represent a single physical device.

 

procedure TMyThread.Execute;
var
  Printer: TPrinter;
begin
  ...
  Printer := TPrinter.Create;
  try
    ...
    while (not Terminated) do
    begin
      ...
      Printer.BeginDoc;
      try
        ...
      finally
        Printer.EndDoc;
      end;
      ...
    end;

  finally
    Printer.Free;
  end;
end;

 

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

×