Converting a Console Application into a GUI that uses a BackgroundWorker

拥有回忆 提交于 2019-12-11 17:53:18

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10746828/converting-a-console-application-into-a-gui-that-uses-a-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!