S
S
samodelkin19902016-01-20 16:16:20
C++ / C#
samodelkin1990, 2016-01-20 16:16:20

Call a form method from a controller?

I am making a program based on the mvc principle in c#, in which the Controller class is first created and a form is created in it and a thread is created. Can you tell me why this code fails after a pause in the thread that is in the Controller class?

public class Controller
  {
    MainForm form;
    
    public Controller()
    {
      form= new MainForm();
      Thread thread= new Thread(new ThreadStart(run));
      thread.Start();
      form.ShowDialog();
    }
    
    public void run(){
      form.addText("Hello!");
                        Thread.Sleep(1000);
            form.addText("Hello2!");
                }
    
    public static void Main(){
      new Controller();
    }
  }

public partial class MainForm : Form
  {
    
    public MainForm()
    {
      InitializeComponent();
    }
    
    
    public void addText(string text){
      this.richTextBox1.Text+= text;
    }
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-01-20
@samodelkin1990

Invoke is used to synchronize with the main thread
form.Invoke(() => { form.addText("Hello!"); })

S
samodelkin1990, 2016-01-20
@samodelkin1990

Mistake:
Illegal operation in multiple threads: Attempted to access a control

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question