-3

I have 2 classes. From my Class 1, I run 10 Threads in Class 2 with some methods in Class 2.

Now the threads are calling a method in my class 1, methods going to execute, checked this with a messagebox. But I have there also a code line for appending some text to a textbox, and this is not getting executed.

I already tried it with an invoke.

Here some snippets:

    private void LaunchButton_Click(object sender, EventArgs e)
    {
        Scanner s = new Scanner(IPText.Text, Convert.ToInt32(Number1Text.Text), Convert.ToInt32(Number2Text.Text), Convert.ToInt32(TimeoutText.Text));
        s.start(Convert.ToInt32(ThreadsText.Text));
    }

at this snippet, I call the start method in class 2.

This method which got called by the threads from class 2:

    public void AktuellerNummer(string Nummer)
    {
        LogText.Invoke(new Action(() =>
        {
            LogText.AppendText("Checking: " + Nummer);
            LogText.ScrollToCaret();
        }));
    }

Here is how the threads call the method ,,AktuellerNummer":

    Class1 class1 = new Class1();
    class1.AktuellerZahl(Zahl.ToString());

Nothing got appended after the call, some guys of you know the reason?

Best regards.

Paul
  • 43
  • 9
  • 1
    In a multi-threaded application, GUI elements can only be modified by the main application thread, so you need to use Invoke(): https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls – LordPupazz May 27 '20 at 15:49
  • I edited my code snippet, so i´ve dont it before with invoke. But i doesnt worked too. @LordPupazz – Paul May 27 '20 at 16:00

1 Answers1

0

Using this code on a test app in an event handler for a button click, it seemed to work just fine. The textbox was populated with lines as expected, might give you some ideas on what to try?:

    new Thread(() =>
    {
        for(int i = 1; i < 20; i++) // simple for loop to simulate different numbers
        {
            Invoke(new Action(() =>
            {
                textBox1.AppendText(string.Format("Checking: {0}{1}", i, Environment.NewLine));
                textBox1.ScrollToCaret();
            }));
            Thread.Sleep(150); // slight delay so we can see things being populated
        }
    }).Start();
LordPupazz
  • 619
  • 3
  • 15
  • If i´m doing it with the invoke i got the following error: Invoke or BeginInvoke cannot be called for a control until the window handle is created. – Paul May 27 '20 at 16:27
  • That would seem to indicate the code is firing before the control has been created on the form. Is that possible in your code? There's an answer to a post with a similar error to this here that might help: https://stackoverflow.com/a/809186/6589412 – LordPupazz May 27 '20 at 16:32
  • I´m going to check this out. Normally it should not be possible in my code, but im working actually with UserControls and found already a lot of differents there – Paul May 27 '20 at 16:58