Answer the question
In order to leave comments, you need to log in
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
Invoke is used to synchronize with the main threadform.Invoke(() => { form.addText("Hello!"); })
Mistake:
Illegal operation in multiple threads: Attempted to access a control
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question