0

I am converting a console application into a Windows Forms Application and a DLL. The Windows Forms Application uses a BackgroundWorker to have the DLL perform a computationally heavy task.

Left over from the console application, the DLL is still littered with Console.WriteLine() statements. I would like to direct what used to be printed to the console into a TextBox in the Windows Form. Ideally, I would like to hook a stream from the DLL up to the text box during form initialization and be done with it. I am concerned that this might not be thread safe with the BackgroundWorker.

The best approach I have found is to change Console.WriteLine() to Trace.WriteLine() in the DLL and then follow the approach at Trace listener to write to a text box (WPF application) but I still have concerns with the BackgroundWorker and am not too keen on appending text to an existing string (there is a lot of text and IMO strings aren't meant/optimized to have lots of text concatenated on them).

What is the best way to print the old console output to the text box that will be safe with a BackgroundWorker?

Community
  • 1
  • 1
chessofnerd
  • 1,219
  • 1
  • 20
  • 40
  • Does it have to print as its generated or can it print all at once at the end ? And the question more concerned with the mechanics of cross thread calls, or with capturing the `Console.WriteLine` output without changing the code ? – Sam Axe May 25 '12 at 00:03
  • I would like it to print as the out put is generated or (more reasonably) when the 'ReportProgress' event is raised. – chessofnerd May 25 '12 at 01:32

1 Answers1

2

The following blog post may be what you're looking for:

http://saezndaree.wordpress.com/2009/03/29/how-to-redirect-the-consoles-output-to-a-textbox-in-c/

I think it describes exactly what you're asking for. Basically it uses Console.SetOut to redirect the console output to a stream writer of your own. Read the comments below the post for some additional information on handling thread issues.