How can I call the function WriteLog
from another thread or class that affects a form control?
using System;
using System.Threading;
using System.Windows.Forms;
namespace DockerManager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
public void WriteLog(string text, bool withdate = true)
{
if (withdate)
{
txtDebugLog.Text = string.Format("{0}\r\n{1}", DateTime.Now.ToString("HH:mm:ss") + ": " + text, txtDebugLog.Text);
}
else
{
txtDebugLog.Text = string.Format("{0}\r\n{1}", text, txtDebugLog.Text);
}
}
private void Form1_Load(object sender, EventArgs e)
{
ControlsWorker.RunWorkerAsync();
}
private void Controls_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
while (!ControlsWorker.CancellationPending)
{
WriteLog("Testing msg");
Thread.Sleep(500);
}
e.Cancel = true;
}
}
}
I want to modify txtDebugLog.Text from a backgroundworker and also from a class like this:
class TestClass
{
Form1.WriteLog("Hello");
}
My idea was doing something like this:
public class TestClass
{
Form1 form = new Form1();
public TestClass(byref form)
{
this.form = form;
this.form.WriteLog("Hello");
}
}
But it's not possible to send a byref argument to a constructor
I'm using this line for calling the method from the backgroundworker and it's working but I don't want to use such a dirty method:
CheckForIllegalCrossThreadCalls = false;
And it's not solving the part of calling the method from another class...