As the other answers say, raise an event that your GUI handles by showing the text of your log. This is a complete example:
1) First of all, think about what data is carried with the event, and extend the EventArgs class to define your class of event arguments. I suppose to output a line that is your log text:
public class LogEventArgs : EventArgs { public string messageEvent {get;set;} }
2) For semplicity, suppose your MyApplication class exposes the business method that you want to use. We will define and raise the event from here. Logging will be a private method that will raise our journal event.
public class MyApplication { public void BusinessMethod(){ this.Logging("first"); System.Threading.Thread.Sleep(1000); this.Logging("second"); System.Threading.Thread.Sleep(3000); this.Logging("third"); } }
3) The implementation of the event. To handle the event, we use a delegate, which is a description of which method declaration should be implemented in the receiver (your GUI) to consume the event and a pointer to the receiver method. We are declaring the OnLogging event. Inside the logging method, we raise an event by setting an argument with a log message. We should check the handler of the non-null event, because if there is no listener for the event, the handle will be null (a null pointer to the method of using the receiver's event).
public delegate void OnLoggingEventHandler(object sender, LogEventArgs e); public event OnLoggingEventHandler OnLogging; private void Logging(string message) { LogEventArgs logMessage = new LogEventArgs(); logMessage.messageEvent = message; if (OnLogging != null) { OnLogging(this, logMessage); } }
4) Now we need to implement an event listener and a method that uses it. Suppose you have a window form with a button that launches your business application method and a text box where the log messages are displayed. This is our form without an event listener and consumer.
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MyApplication myApp = new MyApplication(); myApp.BusinessMethod(); } }
5) We define a consumer method that processes an event that writes in our text field log messages received by the called event. Of course, the method has the same delegate signature.
private void MyApplication_OnLogging(object sender, LogEventArgs e) { this.textBox1.AppendText(e.messageEvent + "\n"); }
6) Using our own C # operator, we bind the OnLogging event to the event user.
private void button1_Click(object sender, EventArgs e) { MyApplication myApp = new MyApplication(); myApp.OnLogging += new MyApplication.OnLoggingEventHandler(MyApplication_OnLogging); myApp.BusinessMethod(); }