0

So using windows form builder, I have created a new form with textbox in it, calling this form as LogForm.cs, this form/class has a method called log(string text).

In my main form class (Form1.cs), I have created an instance of that form.

LogForm logForm = new LogForm();
logForm.log("Logger has started...");

and it show fine on the LogForm textbox. But when I call logForm.log("Some logging info...") On my code inside a thread, it somehow makes my application crash.

How do I deal with this? Please help me demostrate a small code.I am fairly new to C# and programming as a whole so I hope you consider.

  • 5
    Possible duplicate of [How to use multithreading with Winform?](https://stackoverflow.com/questions/6369819/how-to-use-multithreading-with-winform) – Patrick Hollweck Apr 27 '19 at 17:02

1 Answers1

0

Use/call this function in LogForm.log (btw methods in C# are usually capitalized).

private void SetText(string text)
{
    Action set = () => yourTextBox.Text = text;

    if (yourTextBox.InvokeRequired)
    {
        yourTextBox.Invoke(set);
    }
    else
    {
        set.Invoke();
    }
}

If it cannot be set from the current thread yourTextBox.InvokeRequired will be true and the function will work it out. Otherwise it just sets it directly.

Inspiration from this answer at possible duplicate.

Since you are saying the problem persists I'll show a bit more code and try to expain it further.

First of all, I edited the SetText method. I added the private modifier since this function is not indended to be called anywhere outside of LogForm. I also added the curly brackets since that's my preferred style and it also makes sure that the if-statement behaves as expected.

public void Log(string message) {
    SetText(message);
    //do stuff
}

Both of these methods (Log and SetText) are placed inside the LogForm class. You can now call logForm.Log("Logger has started..."); from any thread as long as your form (containing the textbox) is already initialized. This usually happens in the constructor by calling InitializeComponent(); on the first line.

Without knowing more about your code this is probably as far as I can help you.

Joelius
  • 3,839
  • 1
  • 16
  • 36
  • I have done it as you said, but it still not wroking right, it freezes the application and crashes it. – franz gabriel Apr 28 '19 at 02:05
  • Would you consider showing more of your code? I tested the snipped with a normal windows-form and called the method once from the UI-Thread and once from a completely seperate thread. It worked both times. – Joelius Apr 28 '19 at 15:41
  • Check if my edit helps. If not please edit your question and add your definition of the log function which isn't working as expected. – Joelius Apr 28 '19 at 16:02