I working on project and have problem with threading and update of UI. I read many post around web and this site, but didnt find answer to my problem.
I making program that a waiting for some UDP data on port XXXX. Looping in separated thread. When data come he extract information and put it in buffer, and go back wait another data. Another thread routine wait for data in buffer and send it to email.
Because of functionality and code design I have Form1 class (UI) - main thread, Class2 (rutine for reading UDP and extracting data ) - secodn thread, Class3( reading buffer and send mail ) - third thread, Class4 ( Queue buffer ( read, write, delete items ))...
Problem is that when I want to update UI from one of Class I got BufferOwerflow Exception...It's logical because I first must make instance if Class to start threading and in Class I must make instance of Form to pass data, and then we have infinite loop.
All post I found here are about update UI from thread but in same Class. I understand problem about stack and looping because of instances. I just don't want to have one big main class with huge amount of code inside...
Is it posible to update main Form form another class and threading routine inside?
I write some example from head ( it's not working ) just to have clue about what I am talking.
namespace ThreadUIClass
{
public delegate void updateTextBoxDelegate(string text);
public partial class Form1 : Form
{
void updateTextBox(string text)
{
textBox.Text = text;
}
public Form1()
{
InitializeComponent();
Go();
}
public void Go()
{
textBox.Text = "START";
DoWork dW = new DoWork(); //<= instance of work class
Thread myThread = new Thread(dW.WorkInBeckground);
myThread.IsBackground = true;
myThread.Start();
}
}
public class DoWork
{
public void WorkInBeckground()
{
while (true) //loop and wait for data
{
// Listen some ports and get data
// If (data==ok) update main UI textbox with status
Form1 myForm = new Form1(); //<= instance of main class
myForm.Invoke(new updateTextBoxDelegate(???updateTextBox), new object[] { "BUFFER LOADING..." });
Thread.Sleep(1000);
// Continue looping.....
}
}
}
}